Skip to main content

JavaScript Basics


js_alt

Writing a program in JavaScript:

  1. Syntax: the rules to write code
  2. Logic: the code to process data
  3. Input: the data given for processing
  4. Output: the processed data

Printing a string in console:

    • console.log("Hello World");

JavaScript Identifier:

  • Identifier is a name that we give to any reference (for variables, constants, functions, etc.)
  • Any existing JavaScript keyword can not be an identifier.
  • The first letter of an identifier must be either a letter (A-Z, a-z) or an underscore (_), or a dollar sign ($).
  • The rest of the characters can be letters, digits, underscore, or dollar signs.

JavaScript variables:

  • JavaScript variables can be defined using 2 keywords. "var" and "let".
    • var identifierName = "Hello";
    • let identifierName = "Hello";

Difference between var and let:

  • The term "let" was introduced in ES6 (ECMAScript 6) with additional features.
  • The first difference is the scope of the variable. Variables defined as var will have global scope, but variables defined as let will have the block scope (only accessible inside the block they are defined).
  • The second difference is the variables declared as let will not be added to the global window object, so we can't access the variable using the window object, but we can access the variables declared as var using the window object. (window.variableName)
    • var age = 22;
    • function checkAge(a) {
      • var age = 12
      • console.log(age) // prints 12
      • console.log(window.age) // prints 22
    • }
  • variables declared as var can be redeclared, but variables declared as let can't be redeclared.

JavaScript Operators:

  1. Arithmetic operator (+, -, *, /, %, ++a, a++, --b, b--)
  2. Comparison operator (==, !=, >, <, <=, >=) 
  3. logical operator (&&, ||, !)
  4. Bitwise operator (&, |, ~, ^, >>, <<, >>>)
  5. Assignment operator (=, +=, -+, *=, /=, %=)
  6. Conditional operator (condition ? statement 1 : statement 2)
  7. typeof operator (typeof(1) = "Number")

JavaScript loops:

  1. for loop : for (let i = 0; i < 10; i++) { statements }  [Note: i = pointer variable]
  2. for in loop: for (let a in array1) { a = indexes of elements }
  3. for of loop: for (let a of array1) { a = elements of array }
  4. while loop: var i = 0; while (i < 10) { i++ }
  5. do while loop: var i = 0; do { statements } while(i < 10);
  6. break; continue;

JavaScript Conditional Statements:

  1. if else : if (condition) {} else {}
  2. Switch case: Switch(statement) { case1: statement break; case2: statement break; default: statement}

JavaScript Array:

  • Array is a collection of similar type of data.
  • Creating array = let a = [];
  • Adding element end : a.push(element);
  • Removing element end: a.pop();
  • Adding element beginning: a.unshift(element);
  • removing element beginning: a.shift();
  • adding element at position: a.splice(position, 0, element);
  • Delete element at position: a.splice(position, 1);
  • array length: a.length;
  • creating string with format: array.join(divider element);
  • creating string with comma = array.toString();
  • concat array: a.concat(["a","b"]);
  • Getting index of element: indexOf, lastIndexOf;
  • Higher order functions : sort, forEach, filter, every, map, reduce etc.

JavaScript String:

  • String is a collection of characters.
  • Creating a string: "Hello", new String("Hello");
  • String length: a.length
  • To get a character at index: a.charAt(0);
  • To get the ASCII code of the character at index: a.charCodeAt(0);
  • To combine 2 strings: a.concat(b)
  • find index: indexOf(), lastIndexOf()
  • Compare 2 strings: a===b; / a.localCompare(b);
  • change case: toUpperCase(), toLowerCase();
  • substring: substr(start, length) -> legacy (don't use), substring(start, end) -> end not included
  • slicing a string: a.slice(startindex, endindex)
  • splitting string: a.split(" "); a.split("");
  • Replace string character: let a ="apple is round", let regex = "\apple\gi"; a.replace(regex, "orange"); => "orange is round"   -> regex flags: g: global, i: ignore case, m: match over multiple line
  • Matching with regex: a.match(regex)
  • Higher-order functions : forEach
  • important loops: for in, for of.

JavaScript Objects:

  • Key value pairs
  • Creating objects: {}
  • Creating objects 2: let a = new Object(); a.property = value;
  • converting to array: Object.keys(objectname), Object.values(objectname), Object.entries(objectname)
  • Adding a new key value pair: ObjectName["new key"] = new value;
  • Creating constructor function: function abc(a,b,c) {this.a = a; this.b = b; this.c = c;} calling: abc(10,20,30);
  • Creating constructor function 2: function abc(value) {with (this) { a = value }}  calling: abc(10);
  • ex: number , boolean , string , array, math etc.


Comments

Popular posts from this blog

Evaluating Postfix expressions in JavaScript

  Question: Postfix expression evaluation A string containing the postfix expression is given to you. Evaluate it and print the single integer giving the answer. Input Description: The first line of the input is a string N, containing operators and numbers separated by a single space which forms a postfix expression. Output Description: Evaluate the post expression and print the result. Sample Input: 5 3 1 * + 9 - Sample Output: -1 Answer:  Steps to evaluate a prefix expression: Split the prefix expression based on space (" ") or blank string ("") as per the given input. Store the split characters in an array. Create an evaluation array with no elements (blank array). Iterate through the elements of the characters array. If the character is a number, simply push the character into the evaluation array. if the character is an operator (+, -, *, /, %), then pop 2 elements from the evaluation array. Store the first popped number as the right Operand and the second as t...

Find All Permutations of any number in JavaScript.

Question:  Given a string S of length N.  Print all permutations of the string in separate lines. Input Size: 1 <= N <= 100000 Sample Testcases : INPUT: 123 OUTPUT: 123 231 321 213 312 132 Answer:  Steps to find all permutations of any number: We are going to use Recursion for calculating the permutations. Create a method called "getPermutations", and create a Permutations array inside the method that will hold all the permutations. Let's start with the base condition (Where the recursion stops). The base condition will be when the number has only one digit simply add it to the permutations array and return the array. If the number has more digits, then iterate through all the digits. On each iteration, find the current digit (store it in one variable) and find all other digits (store it in another variable). Call the recursive function "getPermutations" and pass the other digits variable created in the above step. We will expect this to return an array of...

HTTP 1.1 vs HTTP 2

HTTP 1.1 vs HTTP 2 Introduction: HTTP (Hypertext Transfer Protocol) is the underlying protocol that powers the World Wide Web. It is a request-response protocol that enables communication between clients and servers. Over the years, HTTP has evolved and seen several versions. The two most widely used versions of HTTP are HTTP1.1 and HTTP2. In this blog, we will explore the differences between HTTP1.1 and HTTP2. Multiplexing: One of the significant differences between HTTP1.1 and HTTP2 is that HTTP2 supports multiplexing, while HTTP1.1 doesn't. Multiplexing allows multiple requests and responses to be sent and received concur...