JavaScript

What is JavaScript ?
  • JavaScript is the Programming Language for the Web.
  • javaScript can update and change both HTML and CSS.
  • JavaScript can calculate, manipulate and validate data.
  • JavaScript is a high-level, interpreted programming language primarily used for creating interactive and dynamic content on websites. 
  • It was first introduced by Netscape in 1995 and quickly became one of the most popular programming languages for web development. 
  • JavaScript allows developers to add behavior, interactivity, and logic to web pages, enabling them to respond to user actions and manipulate the content in real-time.
  • JavaScript code can be written directly in an HTML document using a script tag, or it can be contained in a separate file and linked to the HTML document. 
  • JavaScript code can be executed on both the client-side (in the user's web browser) and the server-side (on the web server).
Here's an example of how JavaScript can be used to change the text color of a website:
<head>
<script>
function changeColor() {
var x = document.getElementById("myText");
x.style.color = "red";
}
</script>
</head>

<body>
<h1 id="myText" onclick="changeColor()">Hello World!</h1>
</body>

In this example, the JavaScript code creates a function that changes the color of the h1 element to red when it is clicked. The onclick attribute in the HTML calls the changeColor() function when the h1 element is clicked.

Where is Javascript used?
Introduction
  • JavaScript is a programming language that is used for creating websites and web-based applications.
  • It is a lightweight language that is easy to learn and use.
  • JavaScript is supported by all modern web browsers, and it can be used in various contexts such as front-end development, server-side programming, and database development.
Front-end Development
  • JavaScript is primarily used for front-end development. It is the language that powers the interactivity of websites.
  • It can be used to create dynamic user interfaces, add interactivity to static content, and create animations and effects.
  • JavaScript frameworks such as React, Angular, and Vue are widely used for building complex web applications. For example, consider the Google Maps application.
  • The Google Maps interface is built using JavaScript. The JavaScript code allows users to interact with the map, add markers, and get directions.
Back-end Development
  • JavaScript can also be used for back-end development. Node.js is a popular platform that enables the use of JavaScript on the server-side.
  • Node.js provides a runtime environment for building web applications using JavaScript.
  • It includes a comprehensive set of modules that simplify the development of server-side applications. For example, consider the LinkedIn application.
  • The LinkedIn back-end is built using Node.js. The Node.js code interacts with the database, processes requests, and generates responses.
Database Development
  • JavaScript can also be used for database development.
  • MongoDB is a popular NoSQL database that uses JavaScript as its query language.
  • MongoDB provides a simple and flexible approach to database design and management, and it enables easy integration with other JavaScript technologies. For example, consider the Trello application.
  • The Trello database is built using MongoDB. The JavaScript code interacts with the MongoDB database, retrieves data, and updates documents.
Summary
  • JavaScript is a versatile language that can be used in various contexts such as front-end development, server-side programming, and database development.
  • The popularity of JavaScript continues to increase, and it is expected to remain a major technology in the world of web development.
  • JavaScript is primarily used for front-end development, but it can also be used for back-end development and database development.
  • Node.js is a popular platform for building server-side applications using JavaScript.
  • MongoDB is a popular NoSQL database that uses JavaScript as its query language.
JavaScript Environment Setup

Install JavaScript Introduction In order to start coding in JavaScript, you need to have it installed on your computer. JavaScript is a client-side scripting language and is widely used in web development to create interactive user interfaces and dynamic web pages. This learning guide will walk you through the steps of installing JavaScript on your machine.
Prerequisites Before installing JavaScript on your computer, ensure that you have the latest version of your preferred web browser installed. JavaScript is supported by most modern web browsers including Chrome, Firefox, Safari, and Edge.
Installing JavaScript JavaScript is usually installed by default when you install your chosen web browser. If for some reason you do not have JavaScript installed, you can follow the below steps to install it.
  1. Go to the official website of the web browser you are using.
  2. Click on the "Download" button to download and install the latest version of your preferred web browser.
  3. Once the download is complete, run the installer and follow the instructions given on the screen.
  4. After the installation is complete, open your web browser and type in "JavaScript" in the search bar. Check if your browser has JavaScript enabled or not. If not, follow the instructions provided by the web browser to enable JavaScript.
  5. Once you have enabled JavaScript, you can start using it to develop interactive web applications.
Conclusion
  • JavaScript is a client-side scripting language that can be used to create dynamic web pages and interactive user interfaces. Installing JavaScript is a simple process because it usually comes pre-installed with most modern web browsers. However, if it is not installed, you can follow the above-mentioned steps to install it on your computer.
Key Takeaways
  • JavaScript is a client-side scripting language that can help you create interactive web pages and user interfaces.
  • Ensure that you have the latest version of your preferred web browser installed. JavaScript is usually pre-installed with most modern web browsers.
  • If JavaScript is not pre-installed, you can follow the same steps used to download and install the web browser.
  • Once installed, check if JavaScript has been enabled on your browser.
Install IDE What is an IDE?
  • IDE stands for Integrated Development Environment.
  • It is a software application that provides a comprehensive suite of program development tools.
  • It typically includes a code editor, a compiler/interpreter, debugging tools, and a graphical user interface.
  • An IDE simplifies the process of software development by providing a single application to manage all aspects of the development process.
Why is it important to install an IDE? An IDE is important to install because it provides an environment that streamlines the development process. IDEs are designed to integrate tools that help debug, compile, and test code, allowing developers to focus on writing code rather than switching between disparate tools.
How do you install an IDE? There are several popular IDEs available for JavaScript, including Visual Studio Code, WebStorm, and Atom. Each IDE has its own installation process, but generally, the following steps are involved: 1. Visit the download page for the IDE you wish to install. 2. Download the installer appropriate for your operating system. 3. Run the installer and follow the prompts. 4. After installation is complete, launch the IDE.
Examples of popular IDEs for JavaScript Visual Studio Code
  • Visual Studio Code, or VS Code, is a free, open-source IDE developed by Microsoft. It supports a variety of programming languages, including JavaScript. It is available for Windows, macOS, and Linux.
WebStorm
  • WebStorm is a commercial IDE developed by JetBrains. It is specifically designed for JavaScript development and includes features such as intelligent code completion and debugging. It is available for Windows, macOS, and Linux.
Atom
  • Atom is a free, open-source IDE developed by GitHub. It supports a variety of programming languages, including JavaScript. It is available for Windows, macOS, and Linux.
Key Takeaways
  • An IDE is an Integrated Development Environment that provides a comprehensive suite of program development tools.
  • IDEs streamline the development process by integrating tools that help debug, compile, and test code.
  • There are several popular IDEs available for JavaScript, including Visual Studio Code, WebStorm, and Atom.
  • Each IDE has its own installation process but generally involves downloading an installer and following the prompts.
Virtual Environments What is a Virtual Environment?
  • A virtual environment is a self-contained environment that has its own isolated Python installation, and can be installed with different packages and modules required by a specific project, without affecting other Python projects. It allows you to create a different environment with different versions of Python, modules, dependencies, etc. which can be used for different applications. For example, If you’re building a web application and need to use a specific version of Flask, but you also have another project that requires a different version of Flask or a different Python version altogether, then using virtual environments can avoid this conflict and let you use each use case with the right dependency version.
How to create a virtual environment
  • Different platforms have different ways of creating a virtual environment. On Linux and Mac, you can use the “venv” module provided by Python, while on Windows, you may have to download and install Python Virtual Environment tools (such as virtualenv) first.
  • On MacOS and Linux, you can run the following command to create a virtual environment:
  • python3 -m venv my_virtual_env
  • In the above example, a new virtual environment named ‘my_virtual_env’ is being created, which can be activated using the following command:
  • source my_virtual_env/bin/activate
  • For Windows, you can create a virtual environment as follows using venv:
  • python -m venv c:\path\to\myenv
Managing dependencies using a virtual environment
  • A virtual environment helps you manage the dependencies required by different projects.
  • Once you’ve created a virtual environment, you can install the packages required by your project in that environment without affecting other shared environments on your computer. To add libraries or modules, use the pip package management system. Within the virtual environment, you can install the needed packages by stating the packages that you need.
  • pip install flask
Activating/Deactivating a virtual environment
  • Once you create a virtual environment, you need to activate it to be able to use it.
  • Use the following command to activate the virtual environment on MacOS and Linux:
  • source my_virtual_env/bin/activate
  • On Windows, run the following command to activate your virtual environment:
  • c:\path\to\myenv\Scripts\activate.bat
To deactivate the virtual environment, simply type the word “deactivate” in your shell.

Key takeaways
  • A Virtual Environment provides you the ability to create an isolated workspace for your project You can create multiple virtual environments having different requirements using different Python versions, packages, and dependencies.
  • You can install different packages to different virtual environments, making sure each project has the dependencies that it requires.
  • You need to activate your virtual environment every time you start working on your project, and you can deactivate it once you’re done.
JavaScript Basics
Variables Introduction Variables are a fundamental concept across all programming languages. A programming variable is a storage location in computer memory that has a specific type, which determines the size and layout of the variable's memory and the range of values that can be stored within that memory. Variables are used to store data values and can be changed or updated throughout the program's execution.
Declaration of Variables
  • In JavaScript, variables can be declared using the "var", "let", or "const" keywords. "var" is the keyword used for variable declaration in earlier versions of JavaScript, but "let" and "const" are preferred in modern JavaScript.
// variable declaration using var keyword var myVar = "Hello world"; // variable declaration using let keyword let myLet = 3; // variable declaration using const keyword const myConst = 3.14; Naming Convention
  • There are certain conventions that you should follow when naming variables in JavaScript.
  • The name of the variable should start with a letter, dollar sign ($), or underscore (_).
  • Following the initial character, variable names can consist of letters, numbers, underscores, or dollar signs.
  • Variable names are case-sensitive in JavaScript.
// valid variable names let myVariable; let _myVariable; let $myVariable; let my_variable; let myVariable2;

Scope of Variables
  • The scope of a variable determines where in the program it can be accessed.
  • Variables declared using the "var" keyword have function-level scope, which means they can be accessed within the function in which they are declared.
  • Variables declared using the "let" and "const" keywords have block-level scope, which means they can only be accessed within the block in which they are declared.
// example of function-level scope function myFunction() { var x = 5; } console.log(x); // throws an error because x is not defined outside the function // example of block-level scope { let y = 10; const z = 15; } console.log(y); // throws an error because y is not defined outside the block console.log(z); // throws an error because z is not defined outside the block 

  Data Types of Variables
  • In JavaScript, there are different data types that variables can hold, such as:
  • Number: represents numeric values
  • String: represents text values
  • Boolean: represents true/false values
  • Null: represents a deliberate non-value
  • Undefined: represents an uninitialized value
  • Object: represents complex entities
  • Symbol: represents unique identifiers
// examples of assigning different data types to variables let myNumber = 42; let myString = "Hello world"; let myBoolean = true; let myNull = null; let myUndefined = undefined; let myObject = { firstName: "John", lastName: "Doe" }; let mySymbol = Symbol("foo");

Assignment of Variables
  • Variables can be assigned a value using the assignment operator (=). The value stored in a variable can be changed or updated by assigning a new value to it.
// assigning a value to a variable let myVariable; myVariable = "Hello world"; // updating the value of a variable myVariable = "Goodbye world";

Key Takeaways
  • Variables are used to store data values and can be changed or updated throughout the program's execution
  • In JavaScript, variables can be declared using the "var", "let", or "const" keywords Variable names should follow certain conventions
  • The scope of a variable determines where in the program
Data Types Introduction
  • Data types in JavaScript refer to the classification of different types of data that can be used in a program.
  • Each data type has its specific rules, properties, and methods that correspond to it.
  • Understanding different data types in JavaScript is essential for effective programming in JavaScript.
Primitive Data Types
  • Primitive Data Types are the Building blocks of JavaScript.
  • These are the most fundamental data types and include Boolean, Null, Undefined, String, Number, and Symbol. They are called primitive data types because they don't refer to existing objects.
// Examples of Primitive Data Types const boolValue = true; const nullValue = null; let undefinedVar; const stringValue = "This is a string"; const numberValue = 100; const symbolValue = Symbol("This is a symbol value"); Non-Primitive Data Types
  • Non-Primitive Data Types are data types that refer to pre-existing objects. The non-primitive data types include Array, Object, and Function. These types can handle large sets of data and can even include data of different types.
// Examples of non-primitive data types const arrayValue = [1,2,3,4,5]; const objectValue = {name:'John', age:22, email:'john@example.com'}; function myFunction() { console.log("This is a function");
} Type Conversion
  • Type conversion refers to the process of changing the data type of a variable into another data type. JavaScript allows you to perform type conversion both automatically and explicitly.
  • Automatic type conversion happens when the script itself converts the data type of a variable, whereas explicit type conversion is done by the programmer.
// Examples of Type Conversion // Automatic const stringValue1 = "10"; // string const numberValue1 = 10; // number const sum = stringValue1 + numberValue1; console.log(sum); // Output: "1010" // Explicit const stringNumberValue = "100"; const numberValue2 = Number(stringNumberValue); console.log(type
of numberValue2); // Output: number Type Coercion
  • Type coercion is the act of converting one data type into another implicitly by the JavaScript interpreter. In JavaScript, if you try to add a numeric value to a string, the interpreter will implicitly convert the numeric value into a string.
// Examples of Type Coercion const sumString = "10" + 20; // Sum is concatenated console.log(sumString); // Output: "1020"
Key Takeaways
  • JavaScript has six primitive data types and three non-primitive data types.
  • Primitive data types are Boolean, Null, Undefined, String, Number, and Symbol, and non-primitive data types are Array, Object, and Function.
  • JavaScript comes with both automatic and explicit type conversion.
  • Type coercion refers to converting one data type into another implicitly by the JavaScript interpreter.
Operators What are Operators?
  • In JavaScript, operators are special symbols that perform operations on values or variables. Operators are used to perform arithmetic, logical, comparison, assignment, and other operations.
Arithmetic Operators
  • Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, division, and modulus. Here are some examples:
let x = 10; let y = 5; console.log(x + y); // Output: 15 console.log(x - y); // Output: 5 console.log(x * y); // Output: 50 console.log(x / y); // Output: 2 console.log(x % y); // Output: 0
Comparison Operators
  • Comparison operators are used to compare two values or variables. They return a boolean value (true or false) based on whether the comparison is true or false. Here are some examples:
let x = 5; let y = 10; console.log(x > y); // Output: false console.log(x < y); // Output: true console.log(x >= y); // Output: false console.log(x <= y); // Output: true console.log(x === y); // Output: false console.log(x !== y); // Output: true

Logical Operators
  • Logical operators are used to combine two or more conditions. They return a boolean value based on whether the conditions are true or false. Here are some examples:
let x = 5; let y = 10; let z = 15; console.log(x < y && x < z); // Output: true console.log(x < y x > z); // Output: true console.log(!(x < y)); // Output: false
Assignment Operators
  • Assignment operators are used to assign values to variables. They combine the assignment operator (=) with arithmetic or logical operators. Here are some examples:
let x = 10; x += 5; // equivalent to x = x + 5; console.log(x); // Output: 15 x -= 3; // equivalent to x = x - 3; console.log(x); // Output: 12 x *= 2; // equivalent to x = x * 2; console.log(x); // Output: 24 x /= 4; // equivalent to x = x / 4; console.log(x); // Output: 6 x %= 5; // equivalent to x = x % 5; console.log(x); // Output: 1 

  Unary Operators
  • Unary operators are operators that require only one operand or variable. They can be used to increment or decrement the value of a variable. Here are some examples:
let x = 5; console.log(++x); // Output: 6 console.log(--x); // Output: 5 console.log(-x); // Output: -5
Key Takeaways
  • Operators are special symbols used to perform operations on values or variables.
  • Arithmetic operators are used to perform mathematical operations.
  • Comparison operators are used to compare two values or variables.
  • Logical operators are used to combine two or more conditions.
  • Assignment operators are used to assign values to variables.
  • Unary
Control Structures Introduction
  • Control structures in JavaScript are constructs that enable the programmer to specify the order in which instructions in a code block are executed.
  • These structures provide decision-making and repetition capabilities in a program, without them, programming the simplest of actions can be incredibly difficult.
If-else statements
  • An if statement is a conditional statement that, if proved true, executes a certain code block. If it is proved false, an optional else statement can be executed instead.
  • Example:
let age = 18; if (age >= 18) { console.log("You are an adult") } else { console.log("You are a minor") } Switch cases
  • Switch case in JavaScript is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of the program to execute particular code block(s). Is typically used when the condition to test is a single value that is compared to multiple possible values, like a variable.
  • Example:
let weekDay = 3; switch (weekDay) { case 1: console.log("Monday"); break; case 2: console.log("Tuesday"); break; case 3: console.log("Wednesday"); break; // ... other cases default: console.log("Invalid day"); break; } For loops
  • A for loop is used when you want to run a piece of code a specific number of times. The 'for' loop includes an initialization of a counter variable, a test condition and an increment/decrement operator.
  • Example:
for (let i = 0; i < 5; i++) { console.log(i); } While loops
  • A while loop will repeatedly run a block of code while a condition remains true. Unlike a for loop, a while loop will continue to iterate until the condition you express returns false.
  • Example:
let i = 0; while (i < 5) { console.log(i); i++; } Do-while loops
  • Do-while is a loop of control statement that executes a block of code at least once, and then either repeatedly executes the block, or stops executing it, depending on a given boolean condition at the end of the block.
  • Example:
let i = 0; do { console.log(i); i++; } while (i < 5); Break and Continue
  • Break and Continue are control statements that are used when looping. The break is used to break a loop while the continue statement is used to skip one iteration in the loop.
  • Example:
for (let i = 0; i < 10; i++) { if (i === 5) { break; } console.log(i); } // Output: 0, 1, 2, 3, 4 Example: for (let i = 0; i < 10; i++) { if (i === 5) { continue; } console.log(i); } // Output: 0, 1, 2, 3, 4, 6, 7, 8, 9 

Key Takeaways
  • Control structures provides decision-making and repetition capabilities in a JavaScript program.
  • An if statement is a conditional statement that executes a certain code block if proved true.
  • A switch case is used when the condition to test is a single value that is compared to multiple
Functions Function Declaration Definition
  • A function declaration is a code block that defines a named or anonymous function. The function declaration ends with a semicolon. Functions are used to group a set of related statements together that can be called repeatedly throughout the program. They can also be used to perform a specific task.
function sum(a, b) { return a + b; } Syntax function functionName(parameters) { // Function body return value; } Examples Example 1: Simple function declaration function greet() { console.log('Hello, world!'); } greet(); Output: Hello, world! Example 2: Function declaration with parameters function add(a, b) { return a + b; var result = add(2, 3); console.log(result); Output: 5 Example 3: Anonymous function declaration var sum = function(a, b) { return a + b; } console.log(sum(2, 3));
Output: 5 Key Takeaways
  • A function declaration is a code block that defines a named or anonymous function.
  • Functions are used to group a set of related statements together that can be called repeatedly throughout the program.
  • They can also be used to perform a specific task.
  • Functions are declared using the `function` keyword.
  • The function declaration ends with a semicolon.
  • The syntax for a function declaration is `function functionName(parameters) { // Function body return value; }`.
  • Functions can take one or more parameters and can also return a value.
  • Anonymous functions are functions without a name and can be assigned to a variable.
Function Expressions

What are Function-Expressions?
  • A Function-Expression is a function that is assigned to a variable or a property of an object.
  • It can be named or anonymous.
  • It is a function that is created at runtime and can be passed as an argument to another function.
//example of a named Function-Expression let square = function(num) { return num * num; }; //example of an anonymous Function-Expression let add = function(a, b) { return a + b; };
How are Function-Expressions used? Function-Expressions are commonly used for following purposes:
  1. To create and assign a function to a variable or property of an object.
  2. To create a closure, i.e., functions within functions that can access the outer functions' variables.
  3. To pass a function as an argument to another function.
  4. To return a function from another function.
//example of a Function-Expression used to create a closure function outerFunction(x) { function innerFunction(y) { return x + y; } return innerFunction; } let add5 = outerFunction(5); console.log(add5(2)); //output: 7 

  How are Function-Expressions different from Function-Declarations?
  • Function-Expressions differ from Function-Declarations in the way they are defined and used.
  • Function-Expressions are defined as a part of an expression, whereas Function-Declarations are defined as standalone statements.
  • Function-Expressions are created at runtime, whereas Function-Declarations are hoisted and can be used before they are declared.
//example of Function-Declaration function square(num) { return num * num; } //example of Function-Expression let square = function(num) { return num * num; }; 

  How to pass a Function-Expression as an argument?
  • Function-Expressions can be passed as arguments to other functions. When we pass a function as an argument, we are not invoking the function.
  • The function is invoked later when it is assigned to a variable or property of an object or called as a callback function.
//example of passing a Function-Expression as an argument function myFunction(fn) { return fn(2, 3); } let sum = function(a, b) { return a + b; }; console.log(myFunction(sum)); //output: 5

How to return a Function-Expression from another function?
  • Function-Expressions can also be returned from another function. When a function returns a Function-Expression, we can call the returned function later when needed.
//example of returning a Function-Expression from another function function greeting(type) { if (type === 'formal') { return function(name) { return 'Hello, ' + name + '. May I help you?'; }; } else if (type === 'informal') { return function(name) { return 'Hi, ' + name + '! What\'s up?'; }; } } let formalGreeting = greeting('formal'); let informalGreeting = greeting('informal'); console.log(formalGreeting('John')); //output: 'Hello, John. May I help you?' console.log(informalGreeting('Jane')); //output: 'Hi, Jane! What's up?'

Key Takeaways
  • Function-Expressions are functions that are assigned to a variable or property of an object. They can be named or anonymous.
  • Function-Expressions can be used to create a closure, pass a function as an
Arrow Functions
What are Arrow Functions?
  • Arrow Functions, also called "Fat Arrow Functions," are a shorthand way of writing function expressions in Javascript.
  • They were introduced in ES6 as a more concise syntax for defining functions.
  • Arrow functions can be written in two ways: a single expression, which can be implicitly returned, or a block of statements, in which case we need to use the `return` keyword.
  • Here's an example of a simple arrow function that takes two parameters and returns their sum:
const sum = (a, b) => a + b; console.log(sum(2, 3)); // Output: 5 Advantages of Arrow Functions Arrow functions have some benefits over traditional functions in Javascript:
  • Shorter syntax: Arrow functions can be written using fewer lines of code than regular functions. This makes them more concise and easier to read.
  • No `this` binding: In traditional functions, the value of `this` depends on how the function was called. This can be confusing and sometimes leads to bugs. In arrow functions, `this` is always the same as the `this` value of the surrounding context.
  • Implicit return: Arrow functions can have an implicit return of a single expression without needing to use the `return` keyword. This makes them more concise and easier to read.
Examples Here are some examples of arrow functions: // With a single argument const double = x => x * 2; console.log(double(4)); // Output: 8 // With multiple arguments const sum = (a, b) => a + b; console.log(sum(2, 3)); // Output: 5 // With multiple statements const multiply = (a, b) => { const result = a * b; return result; }; console.log(multiply(2, 3)); // Output: 6 // Without arguments const sayHello = () => console.log('Hello'); sayHello(); // Output: Hello // With object literals const getPerson = (name, age) => ({ name: name, age: age }); console.log(getPerson('John', 30)); // Output: { name: 'John', age: 30 } 

  Key Takeaways
  • Arrow functions are a shorthand way of writing function expressions in Javascript.'
  • They have a shorter syntax, no `this` binding, and an implicit return.
  • Arrow functions can be written with or without arguments, and with a single expression or multiple statements.
  • The value of `this` in arrow functions is the same as the `this` value of the surrounding context.
  • Arrow functions are a key feature of ES6, and are widely used in modern Javascript programs.
Higher Order Functions
Introduction
  • Higher-order functions is an important concept in functional programming.
  • It is a function that takes one or more functions as arguments, and/or returns a function as its result.
  • In other words, it is a function that operates on functions.
  • In JavaScript, functions are first-class citizens, which means they can be treated like any other value in the language.
  • Functions can be passed around as arguments to other functions, and they can even be returned from functions. This makes higher-order functions possible and very useful.
Functions as Arguments
  • In JavaScript, we can pass functions as arguments to other functions. This is useful when we want to customize the behavior of a function. Here is an example:
function applyOperation(x, y, operation) { return operation(x, y); } function add(x, y) { return x + y; } function subtract(x, y) { return x - y; } console.log(applyOperation(5, 3, add)); // Output: 8 console.log(applyOperation(5, 3, subtract)); // Output: 2
  • In this example, we have two functions, `add` and `subtract`, which take two numbers and return their sum and difference respectively. We also have a function `applyOperation` which takes three arguments, `x`, `y`, and `operation`. `x` and `y` are the numbers that we want to perform an operation on, and `operation` is the function that we want to use to perform the operation.
  • We can pass in either the `add` or `subtract` function as the `operation` argument, depending on what we want to do. The `applyOperation` function will then call the `operation` function and pass in `x` and `y` as arguments.
Functions Returning Functions
  • In JavaScript, functions can also return other functions. This is useful when we want to create functions that are more specialized or customizable. Here is an example:
function createMultiplier(multiplier) { return function (x) { return x * multiplier; }; } const double = createMultiplier(2); const triple = createMultiplier(3); console.log(double(5)); // Output: 10 console.log(triple(5)); // Output: 15
  • In this example, we have a function `createMultiplier` which takes a `multiplier` argument, and returns another function. The returned function takes a single argument `x`, and returns `x` multiplied by the given `multiplier`.
  • We can call the `createMultiplier` function with different values to create different multiplier functions. We can then use these multiplier functions to multiply different numbers.
Key Takeaways
  • Higher-order functions are functions that operate on other functions.
  • In JavaScript, functions are first-class citizens, which means they can be treated like any other value in the language.
  • We can pass functions as arguments to other functions.
  • We can return functions from functions.
  • Higher-order functions are very useful in functional programming.
Object Creation
What is Object Creation in JavaScript? In JavaScript, objects are created using either object literal or constructor functions. Object creation involves defining the properties and methods that the object should have.

Object Literal Creation
  • Object literals are one of the simplest ways of creating objects in JavaScript. With an object literal, you define the object properties and methods in a single structure.
let person = { name: "John Doe", age: 30, getAge: function() { return this.age; } } Constructor Function Creation Constructor functions are another way of creating objects in JavaScript. A constructor function is a template that is used to create new objects with similar properties and methods. function Person(name, age) { this.name = name; this.age = age; this.getAge = function() { return this.age; } } let person1 = new Person("John Doe", 30); Prototype-based Object Creation In JavaScript, objects created using constructor functions are automatically linked to a prototype object. The prototype object is shared among all instances of the object, and provides a way to define properties and methods that are shared between instances. function Person(name, age) { this.name = name; this.age = age; } Person.prototype.getAge = function() { return this.age; } let person1 = new Person("John Doe", 30); Object.create() Method The Object.create() method is another way of creating objects in JavaScript. With Object.create(), you can create a new object with a specified prototype object. let personProto = { getAge: function() { return this.age; } } let person1 = Object.create(personProto); person1.name = "John Doe"; person1.age = 30; 

Key Takeaways
  • Object literals and constructor functions are two ways of creating objects in JavaScript.
  • Constructor functions provide a template for creating new objects with similar properties and methods.
  • Prototype-based object creation provides a way to define properties and methods that are shared among instances of the object.
  • The Object.create() method allows you to create a new object with a specified prototype object.
Object Properties Introduction
  • Objects are one of the most important things in JavaScript. They allow us to store and organize data and functionality.
  • Properties are essential components of objects. In this guide, we will explore the characteristics of object properties.
Object Properties
  • In JavaScript, objects are collections of properties. A property can be a primitive value, an object, or a function. Properties are identified by a name, which is a string.
Creating Object Properties
  • Properties are created by assigning a value to an object. Here's an example of creating an object `person` with two properties, `name` and `age`:
const person = { name: "John Doe", age: 30 } Accessing Object Properties
  • We can access object properties using dot notation (`objectName.propertyName`) or bracket notation (`objectName['propertyName']`).
  • Here's an example of accessing the `name` property of the `person` object created earlier using both notations:
console.log(person.name); // "John Doe" console.log(person['name']); // "John Doe" Modifying Object Properties
  • Object properties can be modified by assigning a new value to the property. Here's an example of modifying the `age` property of the `person` object created earlier:
person.age = 35; console.log(person.age); // 35 Deleting Object Properties
  • Object properties can be deleted using the `delete` keyword. Here's an example of deleting the `age` property of the `person` object created earlier:
delete person.age; console.log(person); // {name: "John Doe"} Property Descriptors
  • Every object property has a property descriptor that defines its behavior. A property descriptor is an object that has the following properties:
  1. `value`: The value of the property.
  2. `writable`: Whether the property can be modified.
  3. `enumerable`: Whether the property can be enumerated. (`for...in` and `Object.keys()`)
  4. `configurable`: Whether the property can be deleted or its descriptor can be modified.
Object.getOwnPropertyDescriptor()
  • The `Object.getOwnPropertyDescriptor()` method can be used to get the descriptor of an object property. Here's an example of using this method to get the descriptor of the `name` property of the `person` object created earlier:
const descriptor = Object.getOwnPropertyDescriptor(person, 'name'); console.log(descriptor); /* { value: "John Doe", writable: true, enumerable: true, configurable: true } */ Object.defineProperty()
  • The `Object.defineProperty()` method can be used to modify the descriptor of an object property.
  • Here's an example of using this method to make the `name` property of the `person` object non-writable:
Object.defineProperty(person, 'name', { writable: false }); person.name = 'Jane Doe'; // Throws an error in strict mode console.log(person.name); // "John Doe"
Key Takeaways
  • Objects in JavaScript are collections of properties.
  • Properties can be primitive values, objects, or functions.
  • Properties are identified by a name, which is a string.
  • We can access object properties using dot notation or bracket notation.
  • Object properties can be modified using assignment.
  • Object properties can be deleted using the `delete` keyword.
  • Object properties have descriptors that define their behavior.
  • The `Object.getOwnPropertyDescriptor()` method can be used to get the descriptor of a property.
  • The `Object.defineProperty()` method can be used
Object Methods What are Object-Methods in Javascript? Object-Methods are functions that are attached to an object and can be called using that object's name. These functions allow us to perform certain operations on the object, which can be helpful in managing and manipulating data. Object-Methods can be used to modify the object's properties, add new properties, or perform more complex logic. Examples of Object-Methods Here are some examples of built-in Object-Methods in JavaScript:
1. Object.keys(): This method returns an array of a given object's own property names. const person = { name: 'John', age: 30 }; const keys = Object.keys(person); console.log(keys); // Output: ['name', 'age'] 2. Object.values():
  • This method is similar to `Object.keys()` but returns an array of a given object's own property values.
const person = { name: 'John', age: 30 }; const values = Object.values(person); console.log(values); // Output: ['John', 30] 3. Object.freeze():
  • This method freezes an object, preventing any new properties from being added or existing properties from being changed.
const person = { name: 'John', age: 30 }; Object.freeze(person); person.age = 31; console.log(person.age); // Output: 30 How to Create Custom Object-Methods
  • We can create our own custom Object-Methods by attaching a function to an object's prototype. Here's an example:
function Employee(name, salary) { this.name = name; this.salary = salary; } Employee.prototype.giveRaise = function(amount) { this.salary += amount; console.log(`New salary for ${this.name}: ${this.salary}`); } const john = new Employee('John', 50000); john.giveRaise(1000); // Output: New salary for John: 51000
  • In this example, we've created a custom `giveRaise()` method for our `Employee` object. This method takes an amount as an argument and adds it to the object's `salary` property.
Conclusion
  • Object-Methods are a powerful tool in JavaScript that allow us to perform various operations on an object.
  • We can use built-in methods like `Object.keys()` and `Object.values()`, or create custom methods using an object's prototype.
  • By mastering Object-Methods, we can write more efficient and readable code.
Key Takeaways
  • Object-Methods are functions that are attached to an object and used to perform operations on the object's properties.
  • Built-in Object-Methods include `Object.keys()`, `Object.values()`, and `Object.freeze()`.
  • Custom Object-Methods can be created using an object's prototype.
  • Object-Methods are helpful in managing and manipulating data.
Prototypes Introduction
  • Every object in JavaScript has a prototype property, which allows objects to inherit properties and methods from their prototypes. Understanding prototypes is essential in JavaScript programming as it enables faster and efficient coding.
Prototype Object
  • A prototype object is an object used as a template to create other objects. Objects are created by extending or inheriting from this prototype object. Every object has an internal prototype property which is assigned to its prototype object.
const person = { firstName: "John", lastName: "Doe", age: 25, fullName: function() { return this.firstName + " " + this.lastName; } }; console.log(person.__proto__); // Output: {} Prototype Chain
  • A prototype chain is a mechanism where objects inherit property and methods from their prototypes. If a property or method does not exist in an object, JavaScript looks for it in the object's prototype and continues to search through the prototype chain until it is found. The chain ends with the Object.prototype object.
function Animal() {} Animal.prototype.type = "Animal"; function Dog() {} Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; Dog.prototype.breed = "Golden Retriever"; const myDog = new Dog(); console.log(myDog.breed); // Output: Golden Retriever console.log(myDog.type); // Output: Animal Constructor Functions
  • Constructor functions are used to create objects in JavaScript, and they also create a prototype object which is then assigned to any objects created using the constructor function. The `new` keyword is used to call the constructor function and create a new object.
function Person(firstName, lastName, age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } Person.prototype.fullName = function() { return this.firstName + " " + this.lastName; } const person1 = new Person("John", "Doe", 25); console.log(person1.fullName()); // Output: John Doe Object.create() Method
  • The `Object.create()` method is used to create a new object and assigns the prototype of an existing object to the newly created object. The created object has access to the properties of the prototype object, so it can inherit these properties and methods.
const person = { firstName: "John", lastName: "Doe", age: 25 } const newPerson = Object.create(person); newPerson.fullName = function() { return this.firstName + " " + this.lastName; } console.log(newPerson.fullName()); // Output: John Doe console.log(newPerson.age); // Output: 25 
  Key Takeaways
  • Prototypes are used as templates to create other objects.
  • All objects in JavaScript have an internal `__proto__` property that is assigned to its prototype object.
  • Prototypes chains enable objects to inherit properties and methods from their prototypes.
  • Constructors create objects and also a prototype object that is assigned to objects created by the constructor.
  • `Object.create()` method creates a new object and assigns the prototype of an existing object to it.
Arrays Array Creation Introduction
  • Arrays are an important data structure in programming that allow you to store and manipulate multiple values in a single variable.
  • Array-creation refers to the process of creating arrays in JavaScript. In this guide, you will learn how to create arrays using different methods and also explore some common pitfalls to avoid.
Creating Arrays
  • There are different ways to create arrays in JavaScript. The simplest way is to use array literals, which consist of square brackets enclosing the values to be stored in the array. For example:
let numbers = [1, 2, 3, 4, 5]; let fruits = ['apple', 'banana', 'orange'];
  • You can also create an array using the `Array()` constructor. This method takes one or more arguments, where each argument represents an element of the array. For example:
let daysOfWeek = new Array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday');
  • Another way to create an array is to use the `Array.from()` method, which creates a new array from an array-like or iterable object. For example:
let colors = Array.from('blue');
  • This creates an array with each character of the string 'blue' as an element.
Common Pitfalls
  • When creating arrays, it's important to be aware of some common pitfalls.
  • One pitfall is creating an array with undefined values, which can happen if you create an array using the `Array()` constructor with a single number argument. For example:
let nums = new Array(3);
  • This creates an array with three undefined values. To initialize the array with specific values, you can either use array literals or fill the array with a specific value using the `Array.fill()` method. For example:
let nums = Array(3).fill(0);
  • This creates an array with three values initialized to 0.
  • Another pitfall is creating an array with non-numeric indices, which can result in unexpected behavior. Array indices in JavaScript must be positive integers or strings that can be converted to positive integers. For example:
let myArray = []; myArray[-1] = 'foo'; console.log(myArray.length);

  • This code creates an array with one property ('-1') and sets its value to 'foo'. However, the `length` property of the array is still 0, which can lead to confusion.
Conclusion
  • Array-creation is an essential skill for any JavaScript programmer.
  • By using array literals, the `Array()` constructor, and the `Array.from()` method, you can create arrays in different ways depending on your specific need. You should also be aware of common pitfalls such as creating arrays with undefined values or non-numeric indices.
  • By avoiding these pitfalls and following best practices, you can create arrays that are efficient, flexible, and easy to work with.
Key Takeaways
  • Array-creation refers to the process of creating arrays in JavaScript.
  • Array literals and the `Array()` constructor are two ways to create arrays in JavaScript.
  • The `Array.from()` method can create an array from an array-like or iterable object.
  • Avoid creating arrays with undefined values or non-numeric indices.
Array Methods Introduction to Array-Methods
  • In Javascript, arrays are ordered lists of values that can be of any data type.
  • In addition to the basic operations like accessing and modifying array values, Javascript comes with a rich set of built-in methods to manipulate arrays.
  • These array methods allow developers to perform complex operations on arrays without needing to write lengthy, custom code. Some of the common array methods are `push()`, `pop()`, `shift()`, `unshift()`, `slice()`, `splice()`, `concat()`, `join()`, `indexOf()`, `find()`, `filter()` and `map()`.
Array Method Syntax
  • Array methods are invoked on an array, and their syntax varies based on the specific method being used. However, most array methods take in one or more arguments and return a new array or modify the original array.
let arr = [1, 2, 3, 4, 5]; arr.push(6); //Pushes a new element to the end of the array. The new length of the array is returned. arr.pop(); //Removes and returns the last element of the array. arr.slice(1, 3); //Returns a new array that contains elements from index 1 to 3 (exclusive) of the original array. arr.splice(2, 1, 'red', 'green'); //Removes one element from index 2 and inserts 'red' and 'green'. Returns an array containing removed elements. arr.concat(6, 7); //Merges two or more arrays and returns the new merged array. arr.join('-'); //Joins all the elements of an array into a string separated by a delimiter. arr.indexOf(3); //Returns the index of the first occurrence of the given item in the array. If not found, returns -1. Mutating vs Non-Mutating Array Methods
  • Some array methods like `push()` and `pop()` modify the existing array, while others like `slice()` and `concat()` return a new array without modifying the original array.
  • It is important to understand whether an array method is mutating or non-mutating in order to use it effectively and avoid unintended side effects.
let arr = [1, 2, 3, 4, 5]; arr.push(6); //mutating method. `arr` is now [1, 2, 3, 4, 5, 6]. arr.slice(1, 3); //non-mutating method. `arr` is still [1, 2, 3, 4, 5].
Common Array Methods push() and pop()
  • `push()` method adds one or more elements to the end of an array and returns the new length of the array. `pop()` method removes and returns the last element of an array.
let arr = ['apple', 'banana']; arr.push('cherry'); //['apple', 'banana', 'cherry']. Returns the new length of the array. arr.pop(); //['apple', 'banana']. Returns the removed element 'cherry'. shift() and unshift()
  • `shift()` method removes and returns the first element of an array, while `unshift()` method adds one or more elements to the beginning of an array and returns the new length of the array.
let arr = ['dog', 'cat', 'hamster']; arr.shift(); //['cat', 'hamster']. Returns the removed element 'dog'. arr.unshift('bird'); //['bird', 'cat', 'hamster']. Returns the new length of the array. splice()
  • `splice()` method can be used
Iteration Methods What are Iteration-Methods?
  • Iteration methods in JavaScript are a way to perform repetitive tasks or iterate over arrays and objects. They allow you to loop through each element or property and execute a block of code for each iteration.
  • There are several methods available in JavaScript for iteration, such as forEach(), map(), filter(), reduce(), and many more.
forEach()
  • The forEach() method is used to call a function for each element in an array. It takes a callback function as its parameter, which is executed for every element in the array.
let numbers = [1, 2, 3, 4, 5]; numbers.forEach(function (number) { console.log(number); }); Output: 1 2 3 4 5

map()
  • The map() method is used to create a new array by calling a function for each element in the original array. The new array contains the values returned by the callback function.
let numbers = [1, 2, 3, 4, 5]; let squaredNumbers = numbers.map(function (number) { return number * number; }); console.log(squaredNumbers); Output: [1, 4, 9, 16, 25] filter()
  • The filter() method is used to create a new array by testing each element in the original array with a callback function. The new array contains the elements that pass the test.
let numbers = [1, 2, 3, 4, 5]; let evenNumbers = numbers.filter(function (number) { return number % 2 === 0; }); console.log(evenNumbers); Output: [2, 4] reduce()
  • The reduce() method is used to reduce an array to a single value by executing a callback function for each element.
  • The callback function takes two parameters, an accumulator and the current element.
  • The accumulator is the result of the previous iteration and the current element is the one being processed.
let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce(function (accumulator, number) { return accumulator + number; }, 0); console.log(sum); Output: 15 Key Takeaways
  • Iteration methods in JavaScript allow you to loop through arrays and objects
  • The forEach() method calls a function for each element in an array
  • The map() method creates a new array by calling a function for each element in the original array
  • The filter() method creates a new array by testing each element in the original array with a callback function
  • The reduce() method reduces an array to a single value by executing a callback function for each element.
Key features of JavaScript include:
  • Client-side Interactivity: JavaScript allows web developers to create interactive elements on web pages, such as forms validation, image sliders, pop-up alerts, and dynamic content updates, without requiring page reloads.
  • DOM Manipulation: JavaScript can access and modify the Document Object Model (DOM), which represents the structure of a web page, enabling developers to change the content and appearance of the page dynamically.
  • Event Handling: JavaScript can handle various events triggered by user interactions (e.g., clicks, keypresses) or other actions (e.g., loading a page) to respond with specific actions or functions.
  • Asynchronous Programming: JavaScript supports asynchronous programming using callbacks, promises, and async/await, allowing developers to perform tasks like making network requests without blocking the rest of the code execution.
  • Cross-platform: JavaScript is supported by all major web browsers, making it a platform-independent language.
  • Extensibility: Developers can extend JavaScript's functionality through libraries and frameworks like React, Angular, and jQuery.
  • Server-side Development: With the advent of Node.js, JavaScript can now be used on the server-side as well, enabling developers to build full-stack applications using the same language.

Post a Comment

1 Comments