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

Understanding How Websites Work and How HTML, CSS, and JavaScript Contribute

Introduction: In today's digital age, websites have become an integral part of our lives. From simple blogs to complex e-commerce platforms, websites have revolutionized the way we interact, communicate, and conduct business online. Behind the scenes, three fundamental technologies play a crucial role in the creation and functionality of websites: HTML, CSS, and JavaScript. In this blog post, we will delve into the workings of websites, exploring the role of each of these technologies and how they contribute to the overall web experience. HTML: The Structure of the Web: HTML (Hypertext Markup Language) forms the backbone of web pages. It is a markup language that defines the structure and content of a webpage. HTML uses tags to enclose various elements, such as headings, paragraphs, images, links, and more. These tags provide a structure and meaning to the content, allowing web browsers to interpret and display them correctly. For example, a simple HTML structure for a webpage migh...

Evaluating Prefix expressions in JavaScript

  Question: Prefix expression evaluation A string containing the prefix expression is given to you. Evaluate it and print the single integer giving the answer. Input Description: You are given a string ‘s’. Output Description: Print the evaluated answer of that string. Sample Input: +23 Sample Output: 5 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 and reverse the 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 left Operand and the second as the right Operand.  Calculate the result using the operands and current operator. [left operand (operator) righ...

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...