{"id":13299608,"url":"https://github.com/RahulSabinkar/javascript-course-notes","last_synced_at":"2025-03-10T11:32:08.927Z","repository":{"id":180760702,"uuid":"463998819","full_name":"RahulSabinkar/javascript-course-notes","owner":"RahulSabinkar","description":"Here I uploaded my exercise programs and notes I wrote using markdown while doing CodeWithMosh's JavaScript Basics Course and learning through various other resources.","archived":false,"fork":false,"pushed_at":"2022-02-28T21:50:18.000Z","size":11,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2023-07-12T18:36:30.943Z","etag":null,"topics":["ecmascript","javascript"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RahulSabinkar.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2022-02-27T00:19:27.000Z","updated_at":"2023-07-12T18:36:32.416Z","dependencies_parsed_at":null,"dependency_job_id":"a59e7cbb-a0e8-408e-bbfc-1dd89dd4141f","html_url":"https://github.com/RahulSabinkar/javascript-course-notes","commit_stats":null,"previous_names":["rahulsabinkar/javascript-course-notes"],"tags_count":null,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RahulSabinkar%2Fjavascript-course-notes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RahulSabinkar%2Fjavascript-course-notes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RahulSabinkar%2Fjavascript-course-notes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RahulSabinkar%2Fjavascript-course-notes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RahulSabinkar","download_url":"https://codeload.github.com/RahulSabinkar/javascript-course-notes/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242843050,"owners_count":20194313,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ecmascript","javascript"],"created_at":"2024-07-29T17:37:45.390Z","updated_at":"2025-03-10T11:32:08.669Z","avatar_url":"https://github.com/RahulSabinkar.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JavaScript Notes \u003c!-- omit in toc --\u003e\n\n## Table Of Contents \u003c!-- omit in toc --\u003e\n\n- [Introduction](#introduction)\n  - [What can you do with JavaScript?](#what-can-you-do-with-javascript)\n  - [Where does JavaScript code run?](#where-does-javascript-code-run)\n  - [JavaScript vs ECMAScript](#javascript-vs-ecmascript)\n- [Basics](#basics)\n  - [Variables](#variables)\n  - [Constants](#constants)\n  - [console.log()](#consolelog)\n  - [Primitive/Value Types](#primitivevalue-types)\n  - [Reference Types](#reference-types)\n    - [Objects](#objects)\n    - [Arrays](#arrays)\n    - [Functions](#functions)\n- [Operators](#operators)\n  - [Arithmetic Operators](#arithmetic-operators)\n  - [Assignment Operators](#assignment-operators)\n  - [Comparison Operators](#comparison-operators)\n  - [Ternary Operator](#ternary-operator)\n  - [Logical Operators](#logical-operators)\n    - [Logical Operator with non-boolean values](#logical-operator-with-non-boolean-values)\n    - [Short-circuiting](#short-circuiting)\n  - [Bitwise Operators](#bitwise-operators)\n  - [Operator Precedence](#operator-precedence)\n  - [Associativity of Operators](#associativity-of-operators)\n- [Control Flow](#control-flow)\n  - [Conditional Statements](#conditional-statements)\n  - [Loop Statements](#loop-statements)\n    - [for...in](#forin)\n    - [for...of](#forof)\n  - [Break and Continue](#break-and-continue)\n    - [break](#break)\n    - [continue](#continue)\n\n---\n\n## Introduction\n\n### What can you do with JavaScript?\n\nFor a long time, JavaScript was only used in Browsers to build interactive web pages. Some developers refered to JavaScript as a toy language. But those days are gone because of huge community support, and investments by large companies like Facebook and Google. These days you can build:\n\n- Web/Mobile Apps\n- Real-time Networking Apps\n  - like chats, video-streaming services, etc\n- Command-Line Tools\n- Games\n\n### Where does JavaScript code run?\n\nJavaScript was originally designed to run only in Browsers. So every browser has a **JavaScript Engine** that can execute JavaScript code.\n\nJavaScript Engines follow the ECMAScript Standards. These standards define how the JavaScript engine should work and what features it should have.\n\nJavaScript Engines for some different Browsers are:\n\n- Firefox: Spidermonkey\n- Chrome: v8\n- Microsoft Edge: Chakra (older version)\n\nIn 2009, Ryan Dahl took the open-source JavaScript Engine in Chrome and embedded it inside a C++ program called **Node**.\n\nDefinition from Wiki:\n\n\u003e Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.\n\n### JavaScript vs ECMAScript\n\nECMAScript is a specification. While JavaScript is a programming language that conforms to these specifications.\n\nECMA is an organisation that is responsible for defining standards.\n\nECMA v1 was released in 1997. Starting from 2015, ECMA has been working on any old releases of newer specifications.\n\nIn 2015, ECMA released ES2015/ES6.\n\n---\n\n## Basics\n\n### Variables\n\nIn the old days, before ES6, we used to use `var` keyword to declare variables. But there are issues with `var`.\n\nSo going forward, from ES6, the best practice is to use `let` keyword to declare variables.\n\nRules for declaring variables:\n\n- cannot be reserved keyword.\n- should be meaningful.\n- cannot start with a number.\n- cannot contain space or hyphen (-).\n- are case-sensitive.\n\nBest Practice:\n\n- use camel-toe notation (Ex: myFirstName).\n- declare/initialise each variable on a single line.\n\n### Constants\n\nIn a real-world application, there are situations when we don't want the value of a variable to change. Otherwise, it's gonna create all kinds of bugs in our application.\n\nIn those situations, when we don't want our variables to change after initialisation, we use `const` instead of `let`.\n\nThe value of a variable can change, but the value of a constant cannot change.\n\n### console.log()\n\nAll modern browsers have a web console for debugging. The console.log() method is used to write messages to these consoles. For example,\n\n```\nlet answer = 5 + 20;\nconsole.log('Sum:', answer); // With a comma\nconsole.log('Sum: ' + answer); // With concantation\n```\n\n### Primitive/Value Types\n\nIn the category of Primitive types we have:\n\n1. string\n   - there are no characters, only strings.\n2. number\n   - no integers or floating points, all are numbers.\n3. boolean\n   - true or false.\n4. undefined\n   - declared but un-initialised variable.\n5. null\n   - used to explicitly clear variable.\n\n`typeof` is an operator that is used to get the type of a variable.\n\n```\nlet name = 'Rahul';        // String Literal\nlet age = 23;              // Number Literal\nlet isApproved = false;    // Boolean Literal\nlet occupation;            // Undefined Variable\nlet selectedCourse = null; // Clearing the Variable\ntypeof name;               // Outputs Type of Variable\n```\n\nUnlike other programming languages, there are no two kinds of numbers like integers and floating points. All numbers come under the type of **number**.\n\n### Reference Types\n\nIn the category of Reference types, we have:\n\n1. objects\n2. arrays\n3. functions\n\n#### Objects\n\nWhen we're dealing with multiple related variables, we can put these variables inside of an object.\n\nFor example, in the code below, we have two variables that are highly related and are part of a representation of a person. So instead of declaring two variables,\n\n```\nlet name = 'Rahul'\nlet age = 23;\n```\n\nwe can declare an object.\n\n```\n// Object Literal\nlet person = {\n    name: 'Rahul',\n    age: 23\n}\n```\n\nThe object _person_ have two _properties_ or _keys_ and those properties have their corresponding property values.\n\nFor example, `name` is a key while `'Rahul'` is a value of that key.\n\nThere are two ways to work with these properties:\n\n1. Dot Notation\n\n```\n`person.name = 'John';\n```\n\n2. Bracket Notation\n\n```\nperson['name'] = 'John';\n```\n\nDot Notation is shorter and concise so it should be the default choice.\n\nHowever, Bracket Notation has it's own uses when we don't know the name of the target property until the run time.\n\n```\nlet selection = 'name';\nperson[selection] = 'Mary';\n```\n\nWith the code above, we can access that property using the Bracket Notation in a **Dynamic** way.\n\n#### Arrays\n\nArray is a data structure that we used to represent a list of items (objects).\n\n```\nlet selectedColors = ['red', 'blue'];\n```\n\nElements inside an array have index values that start with 0.\n\nFor example, the element 'red' in the above code is at index 0, and blue is at index 1.\n\nWe can access those elements inside of an array using those index values.\n\n```\nconsole.log(selectedColors[0]) // Shows output as 'red'\n```\n\nJavaScript is a dynamic language and the length of an array as well as the type of objects we have in our array are dynamic i.e. can be changed at run-time.\n\n```\n// Adds object 'green' to the array\nselectedColors[2] = 'green';\n\n// Arrays can have different types of elements\nselectedColors[3] = '123';\n```\n\nUnlike other statically-typed programming languages where arrays must have same types of elements, in JavaScript we can have different types of elements inside an array.\n\nTechnically, an array is an object and just like with objects, we can access and manipulate elements inside an array using Dot Notation and Bracket Notation.\n\nWhenever we declare an array, that array will automatically receive certain properties like length, push, pop, etc.\n\n```\nnumberOfSelectedColors = selectedColors.length;\n```\n\n#### Functions\n\nFunctions are one of the fundamental building blocks. A function is basically a set of statements that performs a task or calculates a value.\n\nFunction declaration statement doesn't have a semi-colon at the end.\n\n```\n// Function declaration that takes parameter 'name'\n// as input and uses it inside the function block\nfunction greet(name) {\n  console.log('Hello ' + name);\n}\n\nlet name = 'World';\ngreet(name); // Function calling with argument 'name'\n```\n\nWhen we declare a function, we can take one or any number of variables as input which are called **parameters**.\n\nThese parameters are local variables that are only active or usable inside that specific function block. In other words, the scope of these parameters are limited to inside the function.\n\nWhen we call a function, we can pass along one or any number of variables which are called **arguments**.\n\nThe above function was used to _perform a task_. We can also write a function to _calculate a value_ and return a variable.\n\n```\n// Calculating the value and returning the answer\nfunction square(number) {\n  return number * number;\n}\n\n// Calling the function and getting the answer\nconsole.log(square(2));\n```\n\n---\n\n## Operators\n\nIn JavaScript, we have different kinds of Operators. We can use these operators along with our variables and constants to create **expressions**. And with these _expressions_, we can implement _logic_ and _algorithms_.\n\nHere are the different types of Operators in JavaScript:\n\n1. Arithmetic\n2. Assignments\n3. Comparison\n4. Logical\n5. Bitwise\n\n### Arithmetic Operators\n\nArithmetic Operators are used to perform **arithmetic calculations**.\n\n```\nconst number = 3 + 5; // 8\n```\n\nHere, the `+` operator is used to add two operands.\n\n| Operator | Name                       | Example        |\n| -------- | -------------------------- | -------------- |\n| `+`      | Addition                   | `x + y`        |\n| `-`      | Subtraction                | `x - y`        |\n| `*`      | Multiplication             | `x * y`        |\n| `/`      | Division                   | `x / y`        |\n| `%`      | Remainder                  | `x % y`        |\n| `**`     | Exponentiation (Power)     | `x ** y`       |\n| `++`     | Increment (increment by 1) | `++x` or `x++` |\n| `--`     | Decrement (decrement by 1) | `--x` or `x--` |\n\nBoth increment or decrement operators like `++x` and `x++` do different things. For example,\n\n```\nlet x = 10;\n\n// Increment ++\nconsole.log(x++); // 10\nconsole.log(x);   // 11\n\n// Decrement --\nconsole.log(--x); // 9\nconsole.log(x);   // 9\n```\n\n`x++` returns the variable `x` as it is and then increments the variable.\n\nMeanwhile `++x` increments it first and then returns the changed variable.\n\n### Assignment Operators\n\nAssignment operators are used to **assign** values to variables. For example,\n\n```\nconst x = 5;\n```\n\nHere, the `=` operator is used to assign value `5` to variable `x`.\n\nHere's a list of commonly used assignment operators:\n\n| Operator | Name                      | Example                |\n| -------- | ------------------------- | ---------------------- |\n| `=`      | Assignment operator       | `a = 7; // 7`          |\n| `+=`     | Addition assignment       | `a += 5; // a = a + 5` |\n| `-=`     | Subtraction Assignment    | `a -= 2; // a = a - 2` |\n| `*=`     | Multiplication Assignment | `a *= 3; // a = a * 3` |\n| `/=`     | Division Assignment       | `a /= 2; // a = a / 2` |\n| `%=`     | Remainder Assignment      | `a %= 2; // a = a % 2` |\n| `**=`    | Exponentiation Assignment | `a **= 2; // a = a**2` |\n\n### Comparison Operators\n\nComparison operators **compare** two values and return a boolean value, either true or false. For example,\n\n```\nlet a = 5;\nlet b = 3;\n\n// Relational Operators\nconsole.log(a \u003e b);   // true\nconsole.log(a \u003e= b);  // true\nconsole.log(a \u003c b);   // false\nconsole.log(a \u003c= b);  // false\n```\n\nIn JavaScript, there are two Equality Operators. They are:\n\n1. Strict Equality Operator\n   - checks both values and types of the operands.\n2. Loose Equality Operator\n   - checks only the values of the operands.\n\n```\n// Strict Equality Operators\n// Checks both value and type of operands\nconsole.log(1 === 1);   // true\nconsole.log('1' === 1); // false\nconsole.log('1' !== 1); // true\n\n// Loose Equality Operators\n// Checks only value of operands\nconsole.log(1 == 1);  // true\nconsole.log('1' == 1);  // true\nconsole.log('1' != 1);  // false\n```\n\n### Ternary Operator\n\nA ternary operator evaluates a condition and executes a block of code based on the condition.\n\nIt's syntax is:\n\n```\ncondition ? exprIfTrue : exprIfFalse\n```\n\nThe ternary operator evaluates the test condition.\n\n- If the condition is `true`, `exprIfTrue` is executed.\n- If the condition is `false`, `exprIfFalse` is executed.\n\nThe ternary operator takes **three operands**, hence, the name ternary operator. It is also known as a conditional operator.\n\nA ternary operator is frequently used as an alternative to an `if...else` statement in certain situations.\n\nFor example,\n\n```\nlet studentMarks = 70;\nlet evaluation = studentMarks \u003e 60 ? 'pass' : 'fail';\nconsole.log(evaluation); // pass\n```\n\n### Logical Operators\n\nLogical operators perform logical operations and return a boolean value, either true or false.\n\nThere are three Logical Operators in JavaScript, they are:\n\n1. Logical AND\n   - returns `true` only if both operands are `true`.\n2. Logical OR\n   - returns `true` if any operands are `true`.\n3. Logical NOT\n   - returns `true` if the operand is `false` and vice versa\n\n```\nconst x = 5;\nconst y = 3;\n\nconst logicalAnd = (x \u003c 6) \u0026\u0026 (y \u003c 6); // false\nconst logicalOr  = (x \u003c 6) || (y \u003c 6); // true\nconst logicalNot = !logicalAnd;        // true\n```\n\n#### Logical Operator with non-boolean values\n\nIn JavaScript, each value has a type and an inherent **Boolean value**, generally known as either truthy or falsy. Some of the rules that determine how non-Boolean values are translated into true or false values are a little bizarre. Understanding the concepts and their effect on comparison helps when debugging JavaScript applications.\n\nThe following values are **always falsy**:\n\n- `false`\n- `0`\n- `-0`\n- `0n` (`BigInt` zero)\n- `''`, `\"\"`, ` `` ` (Empty String)\n- `null`\n- `undefined`\n- `NaN` (Not A Number)\n\nEverything else is **truthy**. That includes:\n\n- `'0'` (a string containing a single zero)\n- `'false'` (a string containing the text “false”)\n- `[]` (an empty array)\n- `{}` (an empty object)\n- `function(){}` (an “empty” function)\n\nHere's an example,\n\n```\nlet userColor; // undefined\nlet defaultColor = 'red';\nlet selectedColor = userColor || defaultColor;\n\nconsole.log(selectedColor); // red\n\nuserColor = 'blue'; // defined\nselectedColor = userColor || defaultColor;\n\nconsole.log(selectedColor); // blue\n```\n\nIt checks whether userColor is defined, and uses it in that case. If the userColor is not defined, it will use defaultColor.\n\n#### Short-circuiting\n\n```\nconsole.log(false || 1 || 2); // 1\n```\n\nJavaScript Intrepreter only checks the expression til `1` and all the other `||` are ignored completely.\n\n### Bitwise Operators\n\nComputers store numbers in the binary format which is a combination of `0`'s and `1`'s. Every single instruction you write in the programming language is converted into binary format that the computer understands.\n\nThere are two types of Bitwise Operators. They are:\n\n1. Bitwise OR\n2. Bitwise AND\n\nHere below you can see the number `1` and `2` is represented in the binary format\n\n```\n1 = 00000001\n2 = 00000010\nR = 00000011 // Bitwise OR\nA = 00000000 // Bitwise AND\n\nconsole.log(1 | 2); // Bitwise OR\nconsole.log(1 \u0026 2); // Bitwise AND\n```\n\nA real world application can be seen when implementing these concepts in creating an access control system.\n\n```\n// Read Permission\n// 00000100 -\u003e 4\n// Write Permission\n// 00000010 -\u003e 2\n// Execute Permission\n// 00000001 -\u003e 1\n\nconst readPermission = 4;\nconst writePermission = 2;\nconst executePermission = 1;\n\nlet myPermission = 0;\n\n// Giving write and read permissions\nmyPermission = myPermission | writePermission | executePermission;\n\n// Check if user have read permission\nlet message = (myPermission \u0026 readPermission) ? 'Yes' : 'No'\nconsole.log(message) // Yes\n```\n\n### Operator Precedence\n\nOperator precedence determines the order in which the operators in an expression are evaluated.\n\nWhen dealing with multiple operators and operands in a single expression, you can use parentheses for clarity. The expression inside the parentheses is evaluated first.\n\n### Associativity of Operators\n\nIf an expression has two operators with similar precedence, the expression is evaluated according to its associativity (either left to right, or right to left).\n\n---\n\n## Control Flow\n\n### Conditional Statements\n\n- if...else\n  - used when dealing with multiple variables.\n- switch...case\n  - only used when dealing with a single variable.\n\n### Loop Statements\n\nWe have three types of loops that are common with many other programming languages. They are:\n\n1. for\n   - index variable is defined inside for() initialisation section.\n2. while\n   - index variable is defined before while statement.\n   - condition is evaluated first.\n   - statements are executed only if the condition is satisfied.\n   - statements can be executed any number of times including zero.\n3. do...while\n   - index variable is defined before while statement.\n   - condition is evaluated last.\n   - an iteration of statement is executed first, then condition is checked\n   - statements are executed atleast once.\n   - not used a lot in real life scenarios.\n\nIn JavaScript, we have two more types of loops. They are:\n\n1. for...in\n2. for...of\n\n#### for...in\n\nWe use for...in loop to iterate over the **properties** of an object.\n\n```\n// Object with two properties\nconst person = {\n    name: 'Rahul',\n    age: 22\n};\n\n// We use Bracket Notation to access object\n// property values dynamically\nfor (let key in person) {\n    console.log(key, person[key]);\n}\n\n// Array with three elements\nconst colors = [ 'red', 'green', 'blue'];\n\n// Bracket Notation to access those elements\nfor (let index in colors) {\n    console.log(index, colors[index]);\n}\n```\n\nStarting from ES6, even though it is possible to use for...in loop to iterate over the index of an array, it is not recommended as best practice. Ideal way of accessing array elements is through for...of loop.\n\n#### for...of\n\nWe use for...of loop to iterate over the elements or items of an array.\n\n```\n// Array creation with three elements\nconst colors = [ 'red', 'green', 'blue'];\n\n// Accessing array elements\nfor (let color of colors) {\n    console.log(color);\n}\n```\n\n### Break and Continue\n\nThere are two keywords we can use that can change how the loop behaves.\n\n#### break\n\nWe use the `break` keyword to break or jump out of an iteration in a loop. For example,\n\n```\n// To print numbers til 4\nfor (let i=0; i \u003c= 10; i++) {\n    if (i === 5)\n        break;\n    console.log(i);\n}\n```\n\n#### continue\n\nWe use `continue` keyword to skip an interation in a loop. For example,\n\n```\n// To print odd numbers til 10\nfor (let i=0; i \u003c= 10; i++) {\n    if (i % 2 === 0)\n        continue;\n    console.log(i);\n}\n```\n\nIn real-world applications, we don't really use the keyword `continue` that often. It's one of those legacy things in the JavaScript language.\n\nIt's not considered a recommended way of writing code because it leads to a lot of noise in the code. In other words, it's an ugly way of writing code.\n\n---\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRahulSabinkar%2Fjavascript-course-notes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRahulSabinkar%2Fjavascript-course-notes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRahulSabinkar%2Fjavascript-course-notes/lists"}