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

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

Understanding the Difference Between Document and Window Objects

JavaScript Object Introduction: When it comes to building websites, knowing the difference between Document and Window objects in JavaScript is important. These objects work together to make web pages interactive, but they have distinct roles. In this blog, we'll explore what Document and Window objects do and how they differ from each other, and we'll provide code snippets to illustrate their functionalities. Document Object: The Document object represents the web page itself. It lets you access and change the content and structure of the page. When you want to interact with the elements on a page using JavaScript, you'll be working with the Document object. Key features of the Document object include: