diff --git a/LangSidebars.ts b/LangSidebars.ts index b1fac7c..0db123a 100644 --- a/LangSidebars.ts +++ b/LangSidebars.ts @@ -31,11 +31,11 @@ const sidebars: SidebarsConfig = { // JavaScript Tutorial Structure - { - type: "link", - label: "JavaScript", - href: "/languages-platforms/javascript/introduction-to-javascript/what-is-js", - }, + // { + // type: "link", + // label: "JavaScript", + // href: "/languages-platforms/javascript/introduction-to-javascript/what-is-js", + // }, // Java Tutorial Structure @@ -694,80 +694,6 @@ const sidebars: SidebarsConfig = { }, ], - javascript: [ - { - type: "category", - label: "Introduction to JavaScript", - link: { - type: "doc", - id: "javascript/introduction-to-javascript/what-is-js", - }, - items: [ - "javascript/introduction-to-javascript/what-is-js", - "javascript/introduction-to-javascript/history-of-javascript", - "javascript/introduction-to-javascript/javascript-versions", - "javascript/introduction-to-javascript/how-to-run-javascript", - ], - }, - - { - type: "category", - label: "All About Variables", - link: { - type: "doc", - id: "javascript/all-about-variables/variable-declarations", - }, - items: [ - "javascript/all-about-variables/variable-declarations", - "javascript/all-about-variables/variable-naming-rules", - "javascript/all-about-variables/variable-scopes", - "javascript/all-about-variables/hoisting", - ], - }, - - { - type: "category", - label: "Data Types", - link: { - type: "doc", - id: "javascript/data-types/intro", - }, - items: [ - "javascript/data-types/intro", - - { - type: "category", - label: "Primitive Types", - link: { - type: "doc", - id: "javascript/data-types/primitive-types/intro", - }, - items: [ - "javascript/data-types/primitive-types/number", - "javascript/data-types/primitive-types/string", - "javascript/data-types/primitive-types/boolean", - "javascript/data-types/primitive-types/null", - "javascript/data-types/primitive-types/undefined", - "javascript/data-types/primitive-types/symbol", - "javascript/data-types/primitive-types/bigint", - ], - }, - { - type: "category", - label: "Non-Primitive Types", - link: { - type: "doc", - id: "javascript/data-types/non-primitive-types/object/intro", - }, - items: [ - "javascript/data-types/non-primitive-types/object/intro", - "javascript/data-types/non-primitive-types/object/creating-objects", - ], - }, - ], - }, - ], - html: [ "html/intro-html", "html/setup-environment", diff --git a/docs/index.mdx b/docs/index.mdx index ab23bd0..187df62 100644 --- a/docs/index.mdx +++ b/docs/index.mdx @@ -59,7 +59,7 @@ Select a technology below to dive into our structured tutorials. Each path is de

Master styling with CSS. Learn Flexbox, Grid, animations, and responsive design techniques for beautiful interfaces.

- +

From basics to advanced โ€” learn JavaScript programming, DOM manipulation, and ES6+ features to bring interactivity to your projects.

diff --git a/languages-platforms/javascript/all-about-variables/hoisting.mdx b/docs/javascript/all-about-variables/hoisting.mdx similarity index 100% rename from languages-platforms/javascript/all-about-variables/hoisting.mdx rename to docs/javascript/all-about-variables/hoisting.mdx diff --git a/languages-platforms/javascript/all-about-variables/variable-declarations.mdx b/docs/javascript/all-about-variables/variable-declarations.mdx similarity index 100% rename from languages-platforms/javascript/all-about-variables/variable-declarations.mdx rename to docs/javascript/all-about-variables/variable-declarations.mdx diff --git a/languages-platforms/javascript/all-about-variables/variable-naming-rules.mdx b/docs/javascript/all-about-variables/variable-naming-rules.mdx similarity index 100% rename from languages-platforms/javascript/all-about-variables/variable-naming-rules.mdx rename to docs/javascript/all-about-variables/variable-naming-rules.mdx diff --git a/languages-platforms/javascript/all-about-variables/variable-scopes.mdx b/docs/javascript/all-about-variables/variable-scopes.mdx similarity index 100% rename from languages-platforms/javascript/all-about-variables/variable-scopes.mdx rename to docs/javascript/all-about-variables/variable-scopes.mdx diff --git a/languages-platforms/javascript/data-types/intro.mdx b/docs/javascript/data-types/intro.mdx similarity index 100% rename from languages-platforms/javascript/data-types/intro.mdx rename to docs/javascript/data-types/intro.mdx diff --git a/languages-platforms/javascript/data-types/non-primitive-types/object/creating-objects.mdx b/docs/javascript/data-types/non-primitive-types/object/creating-objects.mdx similarity index 100% rename from languages-platforms/javascript/data-types/non-primitive-types/object/creating-objects.mdx rename to docs/javascript/data-types/non-primitive-types/object/creating-objects.mdx diff --git a/languages-platforms/javascript/data-types/non-primitive-types/object/intro.mdx b/docs/javascript/data-types/non-primitive-types/object/intro.mdx similarity index 100% rename from languages-platforms/javascript/data-types/non-primitive-types/object/intro.mdx rename to docs/javascript/data-types/non-primitive-types/object/intro.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/bigint.mdx b/docs/javascript/data-types/primitive-types/bigint.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/bigint.mdx rename to docs/javascript/data-types/primitive-types/bigint.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/boolean.mdx b/docs/javascript/data-types/primitive-types/boolean.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/boolean.mdx rename to docs/javascript/data-types/primitive-types/boolean.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/intro.mdx b/docs/javascript/data-types/primitive-types/intro.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/intro.mdx rename to docs/javascript/data-types/primitive-types/intro.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/null.mdx b/docs/javascript/data-types/primitive-types/null.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/null.mdx rename to docs/javascript/data-types/primitive-types/null.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/number.mdx b/docs/javascript/data-types/primitive-types/number.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/number.mdx rename to docs/javascript/data-types/primitive-types/number.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/string.mdx b/docs/javascript/data-types/primitive-types/string.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/string.mdx rename to docs/javascript/data-types/primitive-types/string.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/symbol.mdx b/docs/javascript/data-types/primitive-types/symbol.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/symbol.mdx rename to docs/javascript/data-types/primitive-types/symbol.mdx diff --git a/languages-platforms/javascript/data-types/primitive-types/undefined.mdx b/docs/javascript/data-types/primitive-types/undefined.mdx similarity index 100% rename from languages-platforms/javascript/data-types/primitive-types/undefined.mdx rename to docs/javascript/data-types/primitive-types/undefined.mdx diff --git a/languages-platforms/javascript/introduction-to-javascript/history-of-javascript.mdx b/docs/javascript/introduction-to-javascript/history-of-javascript.mdx similarity index 100% rename from languages-platforms/javascript/introduction-to-javascript/history-of-javascript.mdx rename to docs/javascript/introduction-to-javascript/history-of-javascript.mdx diff --git a/languages-platforms/javascript/introduction-to-javascript/how-to-run-javascript.mdx b/docs/javascript/introduction-to-javascript/how-to-run-javascript.mdx similarity index 100% rename from languages-platforms/javascript/introduction-to-javascript/how-to-run-javascript.mdx rename to docs/javascript/introduction-to-javascript/how-to-run-javascript.mdx diff --git a/languages-platforms/javascript/introduction-to-javascript/image.png b/docs/javascript/introduction-to-javascript/image.png similarity index 100% rename from languages-platforms/javascript/introduction-to-javascript/image.png rename to docs/javascript/introduction-to-javascript/image.png diff --git a/languages-platforms/javascript/introduction-to-javascript/javascript-versions.mdx b/docs/javascript/introduction-to-javascript/javascript-versions.mdx similarity index 100% rename from languages-platforms/javascript/introduction-to-javascript/javascript-versions.mdx rename to docs/javascript/introduction-to-javascript/javascript-versions.mdx diff --git a/languages-platforms/javascript/introduction-to-javascript/what-is-js.mdx b/docs/javascript/introduction-to-javascript/what-is-js.mdx similarity index 100% rename from languages-platforms/javascript/introduction-to-javascript/what-is-js.mdx rename to docs/javascript/introduction-to-javascript/what-is-js.mdx diff --git a/languages-platforms/javascript/_category_.json b/languages-platforms/javascript/_category_.json new file mode 100644 index 0000000..50456ef --- /dev/null +++ b/languages-platforms/javascript/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "JavaScript", + "position": 3, + "link": { + "type": "generated-index", + "description": "JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. In this tutorial, you'll learn the basics of JavaScript and how to use it to create interactive web experiences." + } +} diff --git a/languages-platforms/javascript/arrays.md b/languages-platforms/javascript/arrays.md new file mode 100644 index 0000000..1fd9c7f --- /dev/null +++ b/languages-platforms/javascript/arrays.md @@ -0,0 +1,476 @@ +--- +id: arrays-in-javascript +title: Arrays in JavaScript for Beginners +sidebar_label: Arrays +sidebar_position: 15 +tags: [JavaScript, Arrays, Array Methods, Array Destructuring, Array Properties, Array Methods, Array Iterators, Array Object, Array Destructuring, Array Length, Access Array Elements, Change Array Elements, Add Array Elements, Remove Array Elements, Loop Through Array, Array Methods, Array Destructuring] +description: "In the JavaScript programming language, arrays are used to store multiple values in a single variable. In this section, you will learn how to create and manipulate arrays in JavaScript. You will also learn about the different methods that can be used to manipulate arrays. We are going to cover the following topics in this section:" +--- + +> Arrays are used to store multiple values in a single variable. They are written with square brackets. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +``` + +## Access the Elements of an Array + +You can access an array element by referring to the index number. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits[0]); // Apple +console.log(fruits[1]); // Banana +console.log(fruits[2]); // Mango +console.log(fruits[3]); // Orange +``` + +## Change an Array Element + +You can change the value of an array element by referring to the index number. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +fruits[0] = "Cherry"; +console.log(fruits); // ["Cherry", "Banana", "Mango", "Orange"] +``` + +## Add an Array Element + +You can add an element to an array using the `push()` method. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +fruits.push("Cherry"); +console.log(fruits); // ["Apple", "Banana", "Mango", "Orange", "Cherry"] +``` + +## Remove an Array Element + +You can remove an element from an array using the `pop()` method. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +fruits.pop(); +console.log(fruits); // ["Apple", "Banana", "Mango"] +``` + +## Array Length + +The `length` property returns the length of an array (number of elements). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits.length); // 4 +``` + +## Loop Through an Array + +You can use a `for` loop to loop through all the elements of an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +for (let i = 0; i < fruits.length; i++) { + console.log(fruits[i]); +} +``` + +## Array Methods + +JavaScript has a number of built-in methods for working with arrays. + +### `toString()` + +The `toString()` method converts an array to a string of (comma separated) array values. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits.toString()); // Apple,Banana,Mango,Orange +``` + +### `join()` + +The `join()` method joins all the elements of an array into a string. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; +console.log(fruits.join(" * ")); // Apple * Banana * Mango * Orange +``` + +### `pop()` + +The `pop()` method removes the last element from an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let lastFruit = fruits.pop(); +console.log(lastFruit); // Orange +console.log(fruits); // ["Apple", "Banana", "Mango"] +``` + +### `push()` + +The `push()` method adds a new element to an array (at the end). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +fruits.push("Cherry"); +console.log(fruits); // ["Apple", "Banana", "Mango", "Orange", "Cherry"] +``` + +### `shift()` + +The `shift()` method removes the first element from an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let firstFruit = fruits.shift(); +console.log(firstFruit); // Apple +console.log(fruits); // ["Banana", "Mango", "Orange"] +``` + +### `unshift()` + +The `unshift()` method adds a new element to an array (at the beginning). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +fruits.unshift("Cherry"); +console.log(fruits); // ["Cherry", "Apple", "Banana", "Mango", "Orange"] +``` + +### `concat()` + +The `concat()` method joins two or more arrays, and returns a new array. + +```js title="index.js" +let fruits1 = ["Apple", "Banana", "Mango", "Orange"]; +let fruits2 = ["Cherry", "Grapes", "Pineapple"]; + +let allFruits = fruits1.concat(fruits2); +console.log(allFruits); // ["Apple", "Banana", "Mango", "Orange", "Cherry", "Grapes", "Pineapple"] +``` + +### `slice()` + +The `slice()` method slices out a piece of an array into a new array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange", "Cherry", "Grapes", "Pineapple"]; + +let citrusFruits = fruits.slice(2, 5); +console.log(citrusFruits); // ["Mango", "Orange", "Cherry"] +``` + +### `splice()` + +The `splice()` method adds/removes items to/from an array, and returns the removed item(s). + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange", "Cherry", "Grapes", "Pineapple"]; + +fruits.splice(2, 2, "Lemon", "Kiwi"); + +console.log(fruits); // ["Apple", "Banana", "Lemon", "Kiwi", "Cherry", "Grapes", "Pineapple"] +``` + +### `sort()` + +The `sort()` method sorts the elements of an array. + +```js title="index.js" +let fruits = ["Banana", "Orange", "Apple", "Mango"]; +console.log(fruits.sort()); // ["Apple", "Banana", "Mango", "Orange"] +``` + +### `reverse()` + +The `reverse()` method reverses the order of the elements in an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.reverse()); // ["Orange", "Mango", "Banana", "Apple"] +``` + +### `indexOf()` + +The `indexOf()` method searches the array for an element and returns its position. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.indexOf("Mango")); // 2 +``` + +### `lastIndexOf()` + +The `lastIndexOf()` method searches the array for an element, starting at the end, and returns its position. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.lastIndexOf("Banana")); // 1 +``` + +### `includes()` + +The `includes()` method checks if an array contains a specified element. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.includes("Mango")); // true +console.log(fruits.includes("Cherry")); // false +``` + +### `find()` + +The `find()` method returns the value of the first element in an array that passes a test (provided as a function). + +```js title="index.js" +let ages = [3, 10, 18, 20]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.find(checkAdult)); // 18 +``` + +### `findIndex()` + +The `findIndex()` method returns the index of the first element in an array that passes a test (provided as a function). + +```js title="index.js" +let ages = [3, 10, 18, 20]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.findIndex(checkAdult)); // 2 +``` + +### `every()` + +The `every()` method checks if all elements in an array pass a test (provided as a function). + +```js title="index.js" +let ages = [32, 33, 16, 40]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.every(checkAdult)); // false +``` + +### `some()` + +The `some()` method checks if some elements in an array pass a test (provided as a function). + +```js title="index.js" +let ages = [3, 10, 18, 20]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.some(checkAdult)); // true +``` + +### `filter()` + +The `filter()` method creates a new array with all elements that pass a test (provided as a function). + +```js title="index.js" +let ages = [32, 33, 16, 40]; + +function checkAdult(age) { + return age >= 18; +} + +console.log(ages.filter(checkAdult)); // [32, 33, 40] +``` + +### `map()` + +The `map()` method creates a new array with the result of calling a function for each array element. + +```js title="index.js" +let numbers = [4, 9, 16, 25]; + +function myFunction(value) { + return value * 2; +} + +console.log(numbers.map(myFunction)); // [8, 18, 32, 50] +``` + +### `reduce()` + +The `reduce()` method reduces the array to a single value (going left-to-right). + +```js title="index.js" +let numbers = [175, 50, 25]; + +function myFunction(total, num) { + return total - num; +} + +console.log(numbers.reduce(myFunction)); // 100 +``` + +### `reduceRight()` + +The `reduceRight()` method reduces the array to a single value (going right-to-left). + +```js title="index.js" +let numbers = [175, 50, 25]; + +function myFunction(total, num) { + return total - num; +} + +console.log(numbers.reduceRight(myFunction)); // -50 +``` + +### `forEach()` + +The `forEach()` method calls a function once for each array element. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +fruits.forEach(function (value, index, array) { + console.log(value); +}); +``` + +### `isArray()` + +The `isArray()` method checks if an object is an array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(Array.isArray(fruits)); // true +``` + +### `from()` + +The `from()` method creates a new Array instance from an array-like or iterable object. + +```js title="index.js" +let myArr = Array.from("ABCDEFG"); + +console.log(myArr); // ["A", "B", "C", "D", "E", "F", "G"] +``` + +### `of()` + +The `of()` method creates a new Array instance with a variable number of arguments. + +```js title="index.js" +let myArr = Array.of(1, 2, 3, 4, 5); + +console.log(myArr); // [1, 2, 3, 4, 5] +``` + +### `fill()` + +The `fill()` method fills the elements of an array with a static value. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.fill("Cherry")); // ["Cherry", "Cherry", "Cherry", "Cherry"] +``` + +### `copyWithin()` + +The `copyWithin()` method copies array elements within the array, to and from specified positions. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +console.log(fruits.copyWithin(2, 0)); // ["Apple", "Banana", "Apple", "Banana"] +``` + +### `entries()` + +The `entries()` method returns a new Array Iterator object that contains the key/value pairs for each index in the array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let iterator = fruits.entries(); + +for (let e of iterator) { + console.log(e); +} +``` + +### `keys()` + +The `keys()` method returns a new Array Iterator object that contains the keys for each index in the array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let iterator = fruits.keys(); + +for (let e of iterator) { + console.log(e); +} +``` + +### `values()` + +The `values()` method returns a new Array Iterator object that contains the values for each index in the array. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let iterator = fruits.values(); + +for (let e of iterator) { + console.log(e); +} +``` + +## Array Destructuring + +Array destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. + +```js title="index.js" +let fruits = ["Apple", "Banana", "Mango", "Orange"]; + +let [first, second, third, fourth] = fruits; + +console.log(first); // Apple +console.log(second); // Banana +console.log(third); // Mango +console.log(fourth); // Orange +``` + +:::info ๐Ÿ“ Note +**Best Practice** + +It is best practice to use the `const` keyword when declaring arrays, as the array values are not expected to change. + + ```js title="index.js" + const fruits = ["Apple", "Banana", "Mango", "Orange"]; + ``` +::: + + +## Conclusion + +In this section, you learned how to create and manipulate arrays in JavaScript. You also learned about the different methods that can be used to manipulate arrays. You can now use arrays to store multiple values in a single variable and perform various operations on them. \ No newline at end of file diff --git a/languages-platforms/javascript/arrow-func-js.md b/languages-platforms/javascript/arrow-func-js.md new file mode 100644 index 0000000..4a4fba5 --- /dev/null +++ b/languages-platforms/javascript/arrow-func-js.md @@ -0,0 +1,164 @@ +--- +id: arrow-function-in-js +title: Arrow Function in JavaScript +sidebar_label: Arrow Function +sidebar_position: 35 +tags: [JavaScript, Arrow Function, ES6, ES2015, ES6 Features, ES2015 Features, ES6 Tutorials, ES2015 Tutorials, ES6 Tutorial, ES2015 Tutorial, ES6 Arrow Function, ES2015 Arrow Function, Arrow Function in JavaScript, Arrow Function in ES6, Arrow Function in ES2015, JavaScript Arrow Function, ES6 Arrow Function Tutorial, ES2015 Arrow Function Tutorial, Arrow Function Tutorial, Arrow Function in JavaScript Tutorial, Arrow Function in ES6 Tutorial, Arrow Function in ES2015 Tutorial, JavaScript Arrow Function Tutorial, ES6 Arrow Function Example, ES2015 Arrow Function Example, Arrow Function Example, Arrow Function in JavaScript Example, Arrow Function in ES6 Example, Arrow Function in ES2015 Example, JavaScript Arrow Function Example, ES6 Arrow Function Syntax, ES2015 Arrow Function Syntax, Arrow Function Syntax, Arrow Function in JavaScript Syntax, Arrow Function in ES6 Syntax, Arrow Function in ES2015 Syntax, JavaScript Arrow Function Syntax, ES6 Arrow Function Syntax Example, ES2015 Arrow Function Syntax Example, Arrow Function Syntax Example, Arrow Function in JavaScript Syntax Example, Arrow Function in ES6 Syntax Example, Arrow Function in ES2015 Syntax Example, JavaScript Arrow Function Syntax Example, ES6 Arrow Function Syntax Tutorial, ES2015 Arrow Function Syntax Tutorial, Arrow Function Syntax Tutorial, Arrow Function in JavaScript Syntax Tutorial, Arrow Function in ES6 Syntax Tutorial, Arrow Function in ES2015 Syntax Tutorial, JavaScript Arrow Function Syntax Tutorial, ES6 Arrow Function Syntax Example Tutorial, ES2015 Arrow Function Syntax Example Tutorial, Arrow Function Syntax Example Tutorial, Arrow Function in JavaScript Syntax Example Tutorial, Arrow Function in ES6 Syntax Example Tutorial, Arrow Function in ES2015 Syntax Example Tutorial, JavaScript Arrow Function Syntax Example Tutorial] +description: "In this tutorial, we will learn about the Arrow Function in JavaScript with the help of examples." +--- + +Arrow Function is a new feature introduced in ES6 (ES2015) that allows you to write shorter function syntax. It provides a more concise way to write functions in JavaScript. + +In this tutorial, you will learn about Arrow Function in JavaScript with the help of examples. + +## Arrow Function Syntax + +The syntax of the Arrow Function is as follows: + +```javascript title="Arrow Function Syntax" +const functionName = (param1, param2, ..., paramN) => { + // function body +}; +``` + +- `functionName`: It is the name of the function. +- `param1, param2, ..., paramN`: These are the parameters of the function. +- `=>`: It is the arrow notation that separates the parameters from the function body. +- `{}`: It contains the function body. +- `return`: If the function body contains a single statement, you can omit the `{}` and `return` keyword. +- `this`: Arrow functions do not have their own `this` value. They inherit the `this` value from the enclosing scope. +- `arguments`: Arrow functions do not have their own `arguments` object. You can use the `arguments` object of the enclosing scope. +- `new`: Arrow functions cannot be used as constructors and will throw an error if you try to use them with the `new` keyword. +- `super`: Arrow functions do not have their own `super` value. They inherit the `super` value from the enclosing scope. +- `prototype`: Arrow functions do not have the `prototype` property. +- `arguments.length`: Arrow functions do not have the `arguments.length` property. +- `new.target`: Arrow functions do not have the `new.target` property. +- `yield`: Arrow functions cannot be used as generators and will throw an error if you try to use them with the `yield` keyword. +- `this` binding: Arrow functions do not bind their own `this` value. They inherit the `this` value from the enclosing scope. + +## Arrow Function Examples + +Let's see some examples to understand how Arrow Functions work in JavaScript. + +### Example 1: Arrow Function with No Parameters + +The following example demonstrates an Arrow Function with no parameters: + +```javascript title="Arrow Function with No Parameters" +const greet = () => { + return 'Hello, World!'; +}; + +console.log(greet()); // Output: Hello, World! +``` + +In this example, the Arrow Function `greet` does not take any parameters and returns the string `'Hello, World!'`. + +### Example 2: Arrow Function with One Parameter + +The following example demonstrates an Arrow Function with one parameter: + +```javascript title="Arrow Function with One Parameter" +const greet = (name) => { + return `Hello, ${name}!`; +}; + +console.log(greet('John')); // Output: Hello, John! +``` + +In this example, the Arrow Function `greet` takes one parameter `name` and returns the string `'Hello, John!'`. + +### Example 3: Arrow Function with Multiple Parameters + +The following example demonstrates an Arrow Function with multiple parameters: + +```javascript title="Arrow Function with Multiple Parameters" + +const add = (a, b) => { + return a + b; +}; + +console.log(add(5, 3)); // Output: 8 +``` + +In this example, the Arrow Function `add` takes two parameters `a` and `b` and returns the sum of the two numbers. + +### Example 4: Arrow Function with a Single Statement + +If the function body contains a single statement, you can omit the `{}` and `return` keyword. The statement will be automatically returned. + +```javascript title="Arrow Function with a Single Statement" +const greet = (name) => `Hello, ${name}!`; + +console.log(greet('John')); // Output: Hello, John! +``` + +In this example, the Arrow Function `greet` takes one parameter `name` and returns the string `'Hello, John!'`. + +### Example 5: Arrow Function with Multiple Statements + +If the function body contains multiple statements, you need to use `{}` and the `return` keyword. + +```javascript title="Arrow Function with Multiple Statements" +const add = (a, b) => { + const sum = a + b; + return sum; +}; + +console.log(add(5, 3)); // Output: 8 +``` + +In this example, the Arrow Function `add` takes two parameters `a` and `b`, calculates the sum of the two numbers, and returns the result. + +### Example 6: Arrow Function with Default Parameters + +You can also use default parameters with Arrow Functions: + +```javascript title="Arrow Function with Default Parameters" +const greet = (name = 'World') => `Hello, ${name}!`; + +console.log(greet()); // Output: Hello, World! + + +console.log(greet('John')); // Output: Hello, John! +``` + +In this example, the Arrow Function `greet` takes one parameter `name` with a default value `'World'` and returns the string `'Hello, World!'` if no argument is passed. + +### Example 7: Arrow Function with Rest Parameters + +You can also use rest parameters with Arrow Functions: + +```javascript title="Arrow Function with Rest Parameters" +const sum = (...numbers) => { + let total = 0; + for (const num of numbers) { + total += num; + } + return total; +}; + +console.log(sum(1, 2, 3, 4, 5)); // Output: 15 +``` + +In this example, the Arrow Function `sum` takes rest parameters `...numbers` and calculates the sum of all the numbers passed as arguments. + +### Example 8: Arrow Function with Object Literal + +You can also return an object literal from an Arrow Function: + +```javascript title="Arrow Function with Object Literal" +const person = (name, age) => ({ name, age }); + +console.log(person('John', 30)); // Output: { name: 'John', age: 30 } +``` + +In this example, the Arrow Function `person` takes two parameters `name` and `age` and returns an object literal with the properties `name` and `age`. + +:::info ๐Ÿ“ Note +When returning an object literal from an Arrow Function, you need to wrap the object literal in parentheses `()` to avoid the confusion with the function body. +::: + +## Conclusion + +In this tutorial, you learned about Arrow Function in JavaScript with the help of examples. Arrow Functions provide a more concise way to write functions in JavaScript. They are a powerful feature introduced in ES6 (ES2015) that allows you to write shorter function syntax. \ No newline at end of file diff --git a/languages-platforms/javascript/basic-js.md b/languages-platforms/javascript/basic-js.md new file mode 100644 index 0000000..474ad7f --- /dev/null +++ b/languages-platforms/javascript/basic-js.md @@ -0,0 +1,118 @@ +--- +id: basic-javascript +title: Basic JavaScript Concepts +sidebar_label: Basic JavaScript +sidebar_position: 3 +tags: [JavaScript, Introduction of js, Introduction of JavaScript, Basic JavaScript Concepts, basic js concepts, basic js] +description: Basic concepts of JavaScript. Learn about displaying output in JavaScript, JavaScript display possibilities, and more. +--- + +In this tutorial, you will learn about the basic concepts of JavaScript. We know that JavaScript is easy to manipulate and can be used to create dynamic content on the web pages. That means JavaScript can be used to change the content of the web page without refreshing the page. Content may be text, images, or any other HTML element. + +**So, let's start with the basic concepts of JavaScript.** + +## Displaying Output in JavaScript + +To display output in JavaScript, we use the `console.log()` method. The `console.log()` method is used to display the output in the console of the web browser. + +```js title="index.js" +console.log('Hello World!'); +``` + +## JavaScript Display Possibilities + +JavaScript can display data in different ways. Here are some of the ways to display data in JavaScript: + +### 1. Alert Box + +The `alert()` method is used to display an alert box with a message and an OK button. + +```js title="index.js" +alert('Hello World!'); +``` + +### 2. Writing into an HTML Element + +The `document.write()` method is used to write into the HTML document. + +```js title="index.js" +document.write('Hello World!'); +``` + +### 3. Writing into the Browser Console + +The `console.log()` method is used to write into the browser console. + +```js title="index.js" +console.log('Hello World!'); +``` + +### 4. Writing into an HTML Element Using `innerHTML` + +The `innerHTML` property is used to write into an HTML element. + +```js title="index.html" + + + + +

+ + + + + +``` + + +

Hello World!

+
+ +### 5. Writing into an HTML Element Using `window.alert()` + +The `window.alert()` method is used to write into an HTML element. + +```js title="index.html" + + + + +

+ + + + + +``` + +### 6. Writing into an HTML Element Using `document.getElementById().innerText` + +The `document.getElementById().innerText` method is used to write into an HTML element. + +```js title="index.html" + + + + +

+ + + + + +``` + + +

Hello World!

+
+ +:::info +**Before moving to the next section, make sure you have a basic understanding of the above concepts.** +You can use any of the above methods to display the output in JavaScript. +::: \ No newline at end of file diff --git a/languages-platforms/javascript/best-practices-js.md b/languages-platforms/javascript/best-practices-js.md new file mode 100644 index 0000000..a91ed4e --- /dev/null +++ b/languages-platforms/javascript/best-practices-js.md @@ -0,0 +1,136 @@ +--- +id: best-practices-in-js +title: Best Practices in JavaScript +sidebar_label: Best Practices +sidebar_position: 41 +tags: + [ JavaScript, Best Practices, Best Practices in JavaScript, JavaScript Best Practices, JavaScript Best Practices Tutorial, JavaScript Best Practices Example, JavaScript Best Practices Coding Standards, JavaScript Best Practices Recommendations, JavaScript Best Practices Conventions, JavaScript Best Practices Rules, JavaScript Best Practices Linting, JavaScript Best Practices ESLint, JavaScript Best Practices Prettier ] +description: "In this tutorial, we will learn about the best practices in JavaScript. We will learn about the coding standards, recommendations, conventions, rules, linting, ESLint, Prettier." +--- + +Best Practices in JavaScript are a set of coding standards, recommendations, conventions, and rules that developers should follow while writing JavaScript code. They help in maintaining the code quality, readability, and consistency across the codebase. They also help in avoiding common pitfalls and bugs in the code. + +There are various tools available for enforcing the best practices in JavaScript such as ESLint, Prettier, etc. These tools help in automatically checking the code against the best practices and providing suggestions or warnings to fix the issues. + +In this tutorial, we will learn about the best practices in JavaScript and how to enforce them using ESLint and Prettier. + +## Best Practices Rules + +The best practices in JavaScript consist of various rules that developers should follow while writing code. These rules cover various aspects of coding such as naming conventions, indentation, spacing, comments, etc. Some common rules in the best practices are: + +### Naming Conventions + +- Use camelCase for variable names. + + + + + ```javascript + let myVariable = 10; + ``` + + + + + ```javascript + let my_variable = 10; + ``` + + + + + +### Indentation + +- Use 2 spaces for indentation. + + + + + ```javascript + if (true) { + console.log("Hello"); + } + ``` + + + + + ```javascript + if (true) { + console.log("Hello"); + } + ``` + + + + + +### Spacing + +- Use spaces around operators. + + + + + ```javascript + let sum = a + b; + ``` + + + + + ```javascript + let sum=a+b; + ``` + + + + + +### Comments + +- Use comments to explain the code. + + + + + ```javascript + // This is a comment + let sum = a + b; // This is an inline comment + ``` + + + + + ```javascript + let sum = a + b; + ``` + + + + + +These are some of the common rules in the best practices in JavaScript. Following these rules helps in writing clean, readable, and maintainable code. + +## Linting + +Linting is the process of analyzing the code for potential errors, bugs, stylistic issues, and enforcing the best practices. ESLint is a popular linting tool for JavaScript that helps in identifying and fixing the issues in the code. + +ESLint can be configured to enforce the best practices rules and provide warnings or errors when the code violates these rules. It helps in maintaining the code quality and consistency across the codebase. + +## Prettier + +Prettier is an opinionated code formatter that helps in automatically formatting the code according to a predefined set of rules. It helps in maintaining a consistent code style across the codebase. + +Prettier can be integrated with ESLint to format the code automatically and enforce the best practices rules. It helps in saving time and effort in manually formatting the code. + +:::info ๐Ÿ“ Info + +In this tutorial, we learned about the best practices in JavaScript. We learned about the coding standards, recommendations, conventions, rules, linting, ESLint, and Prettier. Following the best practices helps in writing clean, readable, and maintainable code. It also helps in avoiding common pitfalls and bugs in the code. + +::: + +## Conclusion + +In this tutorial, we learned about the best practices in JavaScript. We learned about the coding standards, recommendations, conventions, rules, linting, ESLint, and Prettier. Following the best practices helps in writing clean, readable, and maintainable code. It also helps in avoiding common pitfalls and bugs in the code. \ No newline at end of file diff --git a/languages-platforms/javascript/breack-statement.md b/languages-platforms/javascript/breack-statement.md new file mode 100644 index 0000000..f945f63 --- /dev/null +++ b/languages-platforms/javascript/breack-statement.md @@ -0,0 +1,134 @@ +--- +id: breack-statement-in-javascript +title: Break Statement in JavaScript +sidebar_label: Break +sidebar_position: 25 +tags: + [ + JavaScript, + Break, + Statement, + Control, + Flow, + Loop, + Iteration, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the break statement in JavaScript. We will learn how to use the break statement to exit a loop prematurely in JavaScript." +--- + +In JavaScript, the `break` statement is used to exit a loop prematurely. It is often used when you want to terminate the loop based on a certain condition. + +## Syntax + +The syntax of the `break` statement is as follows: + +```js title="app.js" +for (let i = 1; i <= 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +- The `break` statement is used to exit the loop prematurely. +- It can be used inside a `for`, `while`, or `do...while` loop. +- When the `break` statement is encountered, the loop is terminated, and the program continues with the next statement after the loop. +- If the loop is inside a function, the `break` statement will terminate the loop and the function. +- The `break` statement should be used only within a loop, otherwise, it will produce a syntax error. +- The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. +- The `break` statement can be used to avoid an infinite loop by providing a way to exit the loop when a certain condition is met. +- The `break` statement can be used to optimize the performance of a loop by avoiding unnecessary iterations. +- The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. +- The `break` statement can be used to avoid an infinite loop by providing a way to exit the loop when a certain condition is met. + +## Flow Chart of the `break` Statement + +```mermaid +graph LR; + Start([Start]) --> Condition{Condition}; + Condition -- True --> Action1[Action1]; + Condition -- False --> Action2[Action2]; + Action1 --> Break{Break used?}; + Break -- Yes --> End((End)); + Break -- No --> Continue[Continue]; + Continue -- Next --> Condition; + Action2 --> End([End]); + End --> Stop([Stop]); + +``` + +## Example + +The following example demonstrates how to use the `break` statement to exit a loop based on a certain condition: + +```js title="app.js" +for (let i = 1; i <= 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +In this example, the `for` loop initializes the loop variable `i` to `1`. It then checks if `i` is less than or equal to `5`. If the condition is `true`, it executes the code inside the loop and increments `i` by `1`. However, when `i` is equal to `3`, the `break` statement is encountered, and the loop is terminated. The program then continues with the next statement after the loop. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +``` + +In this example, the loop is terminated when `i` is equal to `3`, and the program continues with the next statement after the loop. The numbers `1` and `2` are printed to the console before the loop is terminated. + +The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. It is often used to optimize the performance of a loop by avoiding unnecessary iterations. The `break` statement should be used with caution, as it can make the code harder to read and understand. It is recommended to use the `break` statement sparingly and only when necessary. + +## Example + +The following example demonstrates how to use the `break` statement to exit a loop based on a certain condition: + +```js title="app.js" +let numbers = [1, 2, 3, 4, 5]; +for (let i = 0; i < numbers.length; i++) { + if (numbers[i] === 3) { + break; + } + console.log(numbers[i]); +} +``` + +In this example, the `for` loop iterates over the elements of the `numbers` array. It checks if the current element is equal to `3`. If the condition is `true`, the `break` statement is encountered, and the loop is terminated. The program then continues with the next statement after the loop. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +``` + +In this example, the loop is terminated when the current element is equal to `3`, and the program continues with the next statement after the loop. The numbers `1` and `2` are printed to the console before the loop is terminated. + +The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. It is often used to optimize the performance of a loop by avoiding unnecessary iterations. The `break` statement should be used with caution, as it can make the code harder to read and understand. It is recommended to use the `break` statement sparingly and only when necessary. + +:::tip ๐Ÿค” Remember + +- The `break` statement is used to exit a loop prematurely. +- It can be used inside a `for`, `while`, or `do...while` loop. +- When the `break` statement is encountered, the loop is terminated, and the program continues with the next statement after the loop. +- The `break` statement should be used only within a loop, otherwise, it will produce a syntax error. +- The `break` statement can be used to exit a loop based on a certain condition, such as a specific value or a user input. +- The `break` statement can be used to avoid an infinite loop by providing a way to exit the loop when a certain condition is met. +- The `break` statement can be used to optimize the performance of a loop by avoiding unnecessary iterations. + +::: + +## Summary + +In this tutorial, we learned about the `break` statement in JavaScript. We learned how to use the `break` statement to exit a loop prematurely based on a certain condition. We also learned about the syntax of the `break` statement and how to use it to optimize the performance of a loop. We also learned about the best practices for using the `break` statement and when to use it sparingly. diff --git a/languages-platforms/javascript/classes-js.md b/languages-platforms/javascript/classes-js.md new file mode 100644 index 0000000..ae65fc7 --- /dev/null +++ b/languages-platforms/javascript/classes-js.md @@ -0,0 +1,159 @@ +--- +id: classes-in-js +title: Classes in JavaScript +sidebar_label: Classes +sidebar_position: 36 +tags: [JavaScript, Classes, ES6, ES2015, ES6 Features, ES2015 Features, ES6 Tutorials, ES2015 Tutorials, ES6 Tutorial, ES2015 Tutorial, ES6 Classes, ES2015 Classes, Classes in JavaScript, Classes in ES6, Classes in ES2015, JavaScript Classes, ES6 Classes Tutorial, ES2015 Classes Tutorial, Classes Tutorial, Classes in JavaScript Tutorial, Classes in ES6 Tutorial, Classes in ES2015 Tutorial, JavaScript Classes Tutorial, ES6 Classes Example, ES2015 Classes Example, Classes Example, Classes in JavaScript Example, Classes in ES6 Example, Classes in ES2015 Example, JavaScript Classes Example, ES6 Classes Syntax, ES2015 Classes Syntax, Classes Syntax, Classes in JavaScript Syntax, Classes in ES6 Syntax, Classes in ES2015 Syntax, JavaScript Classes Syntax, ES6 Classes Syntax Example, ES2015 Classes Syntax Example, Classes Syntax Example, Classes in JavaScript Syntax Example, Classes in ES6 Syntax Example, Classes in ES2015 Syntax Example, JavaScript Classes Syntax Example, ES6 Classes Syntax Tutorial, ES2015 Classes Syntax Tutorial, Classes Syntax Tutorial, Classes in JavaScript Syntax Tutorial, Classes in ES6 Syntax Tutorial, Classes in ES2015 Syntax Tutorial, JavaScript Classes Syntax Tutorial, ES6 Classes Syntax Example Tutorial, ES2015 Classes Syntax Example Tutorial, Classes Syntax Example Tutorial, Classes in JavaScript Syntax Example Tutorial, Classes in ES6 Syntax Example Tutorial, Classes in ES2015 Syntax Example Tutorial, JavaScript Classes Syntax Example Tutorial] +description: "In this tutorial, you will learn about classes in JavaScript, a new feature introduced in ES6 (ES2015) that allows you to create objects using the class keyword." +--- + +In JavaScript, classes are a new feature introduced in ES6 (ES2015) that allows you to create objects using the `class` keyword. Classes are a template for creating objects, providing initial values for state and implementations of behavior. + +In this tutorial, you will learn about classes in JavaScript with the help of examples. + +## Classes in JavaScript + +The syntax for defining a class in JavaScript is as follows: + +```javascript title="Class Syntax" +class ClassName { + constructor(param1, param2, ..., paramN) { + // constructor body + } + + method1(param1, param2, ..., paramN) { + // method1 body + } + + method2(param1, param2, ..., paramN) { + // method2 body + } + + // more methods... +} +``` + +- `ClassName`: It is the name of the class. +- `constructor`: It is a special method for creating and initializing objects created with a class. It is called when a new instance of the class is created. +- `method1, method2, ..., methodN`: These are the methods of the class. +- `param1, param2, ..., paramN`: These are the parameters of the constructor and methods. +- `this`: It is a reference to the current instance of the class. +- `new`: It is used to create a new instance of the class. +- `extends`: It is used to create a subclass that inherits from another class. +- `super`: It is used to call the constructor of the parent class. +- `static`: It is used to define static methods on a class. +- `get`: It is used to define a getter method for a property. +- `set`: It is used to define a setter method for a property. +- `prototype`: It is used to add properties and methods to the class prototype. + +## Classes Examples + +Let's see some examples to understand how classes work in JavaScript. + +### Example 1: Creating a Class + +The following example demonstrates how to create a class in JavaScript: + +```javascript title="Creating a Class" +class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + + greet() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +} + +const john = new Person('John', 30); + +console.log(john.greet()); // Output: Hello, my name is John and I am 30 years old. +``` + +In this example, we have defined a class `Person` with a constructor that initializes the `name` and `age` properties of the class. The `greet` method returns a greeting message with the name and age of the person. + +We have created an instance of the `Person` class named `john` and called the `greet` method on it. + +### Example 2: Inheritance in Classes + +The following example demonstrates how to create a subclass that inherits from another class in JavaScript: + +```javascript title="Inheritance in Classes" +class Animal { + constructor(name) { + this.name = name; + } + + speak() { + return `${this.name} makes a sound.`; + } +} + +class Dog extends Animal { + constructor(name, breed) { + super(name); + this.breed = breed; + } + + speak() { + return `${this.name} barks loudly.`; + } +} + +const dog = new Dog('Buddy', 'Labrador'); + +console.log(dog.speak()); // Output: Buddy barks loudly. +``` + +In this example, we have defined a class `Animal` with a constructor that initializes the `name` property and a `speak` method. We have also defined a subclass `Dog` that inherits from the `Animal` class using the `extends` keyword. + +The `Dog` class has its own constructor that initializes the `name` and `breed` properties and overrides the `speak` method to return a different message. + +We have created an instance of the `Dog` class named `dog` and called the `speak` method on it. + +### Example 3: Static Methods in Classes + +The following example demonstrates how to define static methods on a class in JavaScript: + +```javascript title="Static Methods in Classes" +class MathUtils { + static add(a, b) { + return a + b; + } + + static subtract(a, b) { + return a - b; + } +} + +console.log(MathUtils.add(5, 3)); // Output: 8 +console.log(MathUtils.subtract(5, 3)); // Output: 2 +``` + +In this example, we have defined a class `MathUtils` with two static methods `add` and `subtract` that perform addition and subtraction operations, respectively. + +We have called the static methods directly on the class without creating an instance of the class. + +:::info ๐Ÿ“ Note +**Importent Points:** + +- The `constructor` method is a special method that is called when a new instance of the class is created. +- The `this` keyword is used to refer to the current instance of the class. +- The `extends` keyword is used to create a subclass that inherits from another class. +- Static methods are called on the class itself, not on instances of the class. +- The `super` keyword is used to call the constructor of the parent class. +- Getters and setters are used to define getter and setter methods for properties. +- The `prototype` property is used to add properties and methods to the class prototype. +- Arrow functions are not suitable for defining class methods as they do not have their own `this` value. +- Classes in JavaScript are syntactic sugar over the existing prototype-based inheritance model. +- Classes in JavaScript are first-class citizens and can be passed as arguments, returned from functions, and assigned to variables. +- Classes in JavaScript are not hoisted, so they must be defined before they are used. +- Classes in JavaScript can be defined in strict mode or non-strict mode. +- Classes in JavaScript can be defined in the global scope or inside a function. +- Classes in JavaScript can be defined using the `class` keyword or the `function` keyword. +::: + +## Conclusion + +In this tutorial, you learned about classes in JavaScript, a new feature introduced in ES6 (ES2015) that allows you to create objects using the `class` keyword. You also learned about constructors, methods, inheritance, static methods, and other features of classes in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/comments-js.md b/languages-platforms/javascript/comments-js.md new file mode 100644 index 0000000..6b0a45f --- /dev/null +++ b/languages-platforms/javascript/comments-js.md @@ -0,0 +1,101 @@ +--- +id: comments-in-javascript +title: Comments in JavaScript +sidebar_label: Comments in JavaScript +sidebar_position: 6 +tags: [JavaScript, Comments in JavaScript, comments in js, JavaScript comments] +description: Write comments in JavaScript to explain the code and make it more readable. Learn about single-line comments and multi-line comments in JavaScript. +--- + +In this tutorial, you will learn about comments in JavaScript. Comments are used to explain the code and make it more readable. They are ignored by the JavaScript interpreter. + +There are two types of comments in JavaScript: + +1. Single-line comments +2. Multi-line comments + +## Single-line Comments + +Single-line comments start with `//`. They are used to add comments to a single line. + +For example, + +```js title="single-line-comments.js" +// This is a single-line comment + +console.log("Hello, World!"); // Output: Hello, World! +``` + +## Multi-line Comments + +Multi-line comments start with `/*` and end with `*/`. They are used to add comments to multiple lines. + +For example, + +```js title="multi-line-comments.js" +/* +This is a multi-line comment +It can span multiple lines +*/ + +console.log("Hello, World!"); // Output: Hello, World! +``` + +In this example, the multi-line comment spans multiple lines. + +**Now Let's Get Started with html** + +```html title="index.html" + + + + + + Comments in JavaScript + + +

Comments in JavaScript

+

Open the console to see the output.

+ + + +``` + +In this example, we have added a single-line comment and a single-line comment at the end of the line. + +**Now Let's Get Started with multi-line comments** + +```html title="index.html" + + + + + + Comments in JavaScript + + +

Comments in JavaScript

+

Open the console to see the output.

+ + + +``` + +In this example, we have added a multi-line comment that spans multiple lines. + +:::note +Comments are used to explain the code and make it more readable. They are ignored by the JavaScript interpreter. +::: + +## Conclusion + +In this tutorial, you learned about comments in JavaScript. You learned about single-line comments and multi-line comments. Comments are used to explain the code and make it more readable. They are ignored by the JavaScript interpreter. \ No newline at end of file diff --git a/languages-platforms/javascript/const-js.md b/languages-platforms/javascript/const-js.md new file mode 100644 index 0000000..3252f5b --- /dev/null +++ b/languages-platforms/javascript/const-js.md @@ -0,0 +1,151 @@ +--- +id: const-in-javascript +title: Const Keyword in JavaScript +sidebar_label: Const Keyword +sidebar_position: 9 +tags: [JavaScript, const, ES6, Variables, Block Scope, Hoisting, Redeclaration, Best Practices, Comparison, let, var, Constants, ECMAScript 6, ES6, ES2015, Syntax, Example, Block Scope, Reassignment, Best Practices, Comparison with let, Comparison with var, Hoisting, Summary] +description: What is the const keyword in JavaScript and how to use it. +--- + +In JavaScript, the `const` keyword is used to declare a block-scoped variable that cannot be reassigned. It was introduced in ECMAScript 6 (ES6) and is the preferred way to declare constants in modern JavaScript. + +> ***ES6 (ECMAScript 2015) is a major update to JavaScript that adds new syntax and features to the language. It was officially released in June 2015.*** + +## Syntax + +The syntax to declare a constant using the `const` keyword is: + +```js title="Syntax" +const variableName = value; +``` + +Here, `variableName` is the name of the constant and `value` is the value assigned to the constant. + +## Example + +Let's see an example to understand how to use the `const` keyword in JavaScript: + +```js title="Example" +const PI = 3.14159; +console.log(PI); // Output: 3.14159 +``` + +In the above example, we have declared a constant `PI` using the `const` keyword and assigned it a value `3.14159`. We then printed the value of the constant using `console.log()`. + +## Block Scope + +The `const` keyword is block-scoped, which means that the constant declared using `const` is only available within the block in which it is defined. + +```js title="Block Scope" +{ + const x = 10; + console.log(x); // Output: 10 +} + +console.log(x); // Uncaught ReferenceError: x is not defined +``` + +In the above example, the constant `x` is only available within the block in which it is defined. If we try to access it outside the block, it will result in a `ReferenceError`. + +## Reassignment + +The `const` keyword does not allow reassignment of the same constant once it has been initialized. + +```js title="Reassignment" +const x = 10; +x = 20; // Uncaught TypeError: Assignment to constant variable. +``` + +In the above example, we are trying to reassign the value of the constant `x`, which results in a `TypeError`. + +## Best Practices + +- Use the `const` keyword for values that are not intended to be reassigned. +- Use descriptive variable names to improve code readability. +- Use uppercase letters and underscores to name constants (e.g., `MAX_LENGTH`, `PI`, `TAX_RATE`). +- Avoid using `const` for complex objects or arrays, as it only prevents reassignment of the variable itself, not its properties or elements. +- Use `let` or `var` for values that need to be reassigned. +- Use `const` for values that are known at compile time and are not expected to change. +- Use `const` for function expressions, arrow functions, and classes to prevent accidental reassignment. +- Use `const` for values that are shared across multiple files or modules. +- Use `const` for values that are used as configuration settings or constants in your application. +- Use `const` for values that are used as default parameters in functions. + +## Comparison with let + +The `const` keyword is similar to the `let` keyword in that it is block-scoped and cannot be hoisted. However, the main difference is that a variable declared using `const` cannot be reassigned, whereas a variable declared using `let` can be reassigned. + +```js title="Comparison with let" +const x = 10; +x = 20; // Uncaught TypeError: Assignment to constant variable + +let y = 10; +y = 20; // No error +``` + +In the above example, we are trying to reassign the value of the constant `x`, which results in a `TypeError`. However, we can reassign the value of the variable `y` without any error. + +## Comparison with var + +The `const` keyword differs from the `var` keyword in terms of block scope, reassignment, and hoisting. + +### Block Scope + +Variables declared using the `var` keyword are function-scoped or globally-scoped, whereas variables declared using the `const` keyword are block-scoped. + +```js title="Block Scope" +// var +function varExample() { + if (true) { + var x = 10; + } + console.log(x); // Output: 10 +} + +// const + +{ + const y = 10; + console.log(y); // Output: 10 +} + +console.log(y); // Uncaught ReferenceError: y is not defined +``` + +In the above example, the variable `x` declared using the `var` keyword is available outside the block in which it is defined, whereas the constant `y` declared using the `const` keyword is not available outside the block. + +### Redeclaration + +The `var` keyword allows redeclaration of the same variable within the same block scope, whereas the `const` keyword does not allow redeclaration of the same constant within the same block scope. + +```js title="Redeclaration" +var x = 10; +var x = 20; // No error + +const y = 10; +const y = 20; // Uncaught SyntaxError: Identifier 'y' has already been declared +``` + +In the above example, we are trying to redeclare the variable `x` using the `var` keyword, which does not result in an error. However, we are trying to redeclare the constant `y` using the `const` keyword, which results in a `SyntaxError`. + +### Hoisting + +Variables declared using the `var` keyword are hoisted to the top of their function or global scope, whereas variables declared using the `const` keyword are not hoisted. + +```js title="Hoisting" +console.log(x); // Output: undefined +var x = 10; + +console.log(y); // Uncaught ReferenceError: y is not defined +const y = 10; +``` + +In the above example, the variable `x` declared using the `var` keyword is hoisted to the top of the global scope, whereas the constant `y` declared using the `const` keyword is not hoisted. + +:::info ๐Ÿ“ Note +It is recommended to use the `const` keyword for values that are not intended to be reassigned and are known at compile time. This helps prevent accidental reassignment and improves code readability. +::: + +## Summary + +Constants are block-scoped variables that cannot be reassigned once they are initialized. The `const` keyword is used to declare constants in JavaScript and is the preferred way to declare constants in modern JavaScript. It is similar to the `let` keyword in terms of block scope and hoisting, but it differs in that it does not allow reassignment. It also differs from the `var` keyword in terms of block scope, redeclaration, and hoisting. It is recommended to use the `const` keyword for values that are not intended to be reassigned and are known at compile time. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/_category_.json b/languages-platforms/javascript/datatypes/_category_.json new file mode 100644 index 0000000..35b5974 --- /dev/null +++ b/languages-platforms/javascript/datatypes/_category_.json @@ -0,0 +1,9 @@ +{ + "label": "Data Types in JavaScript", + "position": 11, + "link": { + "type": "generated-index", + "description": + "Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in JavaScript, data types are divided into two categories: primitive data types and object data types. Primitive data types are the most basic data types available in JavaScript. They are the building blocks for data manipulation. Object data types are more complex data types and are used to store collections of data and more complex entities." + } + } \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/datatypes-js.md b/languages-platforms/javascript/datatypes/datatypes-js.md new file mode 100644 index 0000000..6f571ae --- /dev/null +++ b/languages-platforms/javascript/datatypes/datatypes-js.md @@ -0,0 +1,217 @@ +--- +id: datatypes-in-javascript +title: Data Types in JavaScript +sidebar_label: Data Types +sidebar_position: 1 +tags: [JavaScript, Data Types, Primitive Data Types, Non-Primitive Data Types, String, Number, BigInt, Boolean, Undefined, Symbol, 'Null', Object, Array, Function, Type Conversion, Implicit Type Conversion, Explicit Type Conversion] +description: What is the data type in JavaScript? Learn about the primitive and non-primitive data types in JavaScript, including string, number, bigint, boolean, undefined, symbol, null, object, array, and function. +--- + +Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in JavaScript, data types are divided into two categories: + +1. **Primitive Data Types** +2. **Non-Primitive Data Types** + +## Primitive Data Types + +JavaScript has seven primitive data types: `string`, `number`, `bigint`, `boolean`, `undefined`, `symbol`, and `null`. + +### 1. String Data Type + +```js title="index.js" +let name = "John Doe"; +let message = 'Hello World!'; +``` + +### 2. Number Data Type + +The number data type is used to represent numeric values. It can be an integer or a floating-point number. For example: + +```js title="index.js" +let count = 100; +let price = 99.99; +``` + +### 3. Boolean Data Type + +The boolean data type represents a logical value. It can have only two values: `true` or `false`. For example: + +```js title="index.js" +let isTrue = true; +let isFalse = false; +``` + +### 4. Undefined Data Type + +The `undefined` data type represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. For example: + +```js title="index.js" +let data; +console.log(data); // Output: undefined +``` + +### 5. Null Data Type + +The `null` data type represents a null value. In JavaScript, `null` is not a reference to a non-existing object. It is simply a special value that represents "nothing", "empty", or "value unknown". For example: + +```js title="index.js" +let car = null; +``` + +### 6. Symbol Data Type + +The `symbol` data type represents a unique and immutable value and may be used as the key of an `Object` property. For example: + +```js title="index.js" +let id = Symbol('id'); +``` + +### 7. BigInt Data Type + +The `bigint` data type is used to represent whole numbers larger than `2^53 - 1`. It is a new feature in JavaScript and is not supported in all browsers. For example: + +```js title="index.js" +let value = 9007199254740991n; +``` + +## Non-Primitive Data Types + +Non-primitive data types are called reference types because they are accessed by reference. These data types are `Object`, `Array`, and `Function`. + +### 1. Object Data Type + +The `object` data type represents a collection of key-value pairs. For example: + +```js title="index.js" +let person = { + name: 'John Doe', + age: 25 +}; + +console.log(person.name); // Output: John Doe +``` + +### 2. Array Data Type + +The `array` data type represents a list of elements. For example: + +```js title="index.js" +let colors = ['red', 'green', 'blue']; +console.log(colors[0]); // Output: red +``` + +### 3. Function Data Type + +The `function` data type represents a function. For example: + +```js title="index.js" +function greet(name) { + return `Hello, ${name}!`; +} + +console.log(greet('John Doe')); // Output: Hello, John Doe! +``` + +## Type Conversion + +Type conversion is the process of converting the value from one data type to another. JavaScript provides two types of type conversion: + +1. **Implicit Type Conversion** +2. **Explicit Type Conversion** + +### 1. Implicit Type Conversion + +Implicit type conversion, also known as type coercion, is the automatic conversion of data types. For example: + +```js title="index.js" +let x = 10; +let y = "5"; +let z = x + y; + +console.log(z); // Output: 105 +``` + +In the above example, the number `10` is converted to a string and concatenated with the string `"5"`. + +### 2. Explicit Type Conversion + +Explicit type conversion, also known as type casting, is the manual conversion of data types. For example: + +```js title="index.js" +let x = "10"; +let y = 5; +let z = Number(x) + y; + +console.log(z); // Output: 15 +``` + +In the above example, the string `"10"` is converted to a number and added to the number `5`. + +:::tip tips and tricks +- In JavaScript, you can use the `Number()`, `String()`, `Boolean()`, and `BigInt()` functions to convert a value to a number, string, boolean, and bigint, respectively. +- The `parseInt()` and `parseFloat()` functions are used to convert a string to an integer and floating-point number, respectively. +::: + +:::info note +**1. Difference between primitive and non-primitive data types:** + +|No. |Primitive Data Types|Non-Primitive Data Types| +|--- |--- |--- | +|1. |Primitive data types are immutable.|Non-primitive data types are mutable.| +|2. |Primitive data types are stored in the stack.|Non-primitive data types are stored in the heap.| +|3. |Primitive data types are accessed by value.|Non-primitive data types are accessed by reference.| + +**2. Type conversion in JavaScript:** + +|No. |Implicit Type Conversion|Explicit Type Conversion| +|--- |--- |--- | +|1. |Implicit type conversion is the automatic conversion of data types.|Explicit type conversion is the manual conversion of data types.| +|2. |Implicit type conversion is performed by JavaScript.|Explicit type conversion is performed by the developer.| +|3. |Implicit type conversion is also known as type coercion.|Explicit type conversion is also known as type casting.| + +**3. Difference between pass by value and pass by reference:** + +|No. |Pass by Value|Pass by Reference| +|--- |--- |--- | +|1. |In pass by value, a copy of the actual value is passed to the function.|In pass by reference, the actual value is passed to the function.| +|2. |Pass by value is used for primitive data types.|Pass by reference is used for non-primitive data types.| +|3. |Pass by value is used in JavaScript for primitive data types.|Pass by reference is used in JavaScript for non-primitive data types.| +|4. |Pass by value is faster than pass by reference.|Pass by reference is slower than pass by value.| +|5. |Pass by value is used in the stack.|Pass by reference is used in the heap.| + +6. for example: + ```js title="pass by value" + let x = 10; + let y = x; + x = 20; + console.log(y); // Output: 10 + ``` + --- + + ```js title="Pass by Reference" + let person = { + name: 'Ajay Dhangar', + age: 25 + }; + let p = person; + person.name = 'Jane Doe'; + console.log(p.name); // Output: Jane Doe + ``` + +**4. Difference between `null` and `undefined`:** + +|No. |null|undefined| +|--- |--- |--- | +|1. |`null` represents a null value.|`undefined` represents an undefined value.| +|2. |`null` is an object.|`undefined` is a type.| +|3. |`null` is assigned to a variable.|`undefined` is the value of a variable that has not been assigned a value.| +|4. |`null` is used to represent "nothing", "empty", or "value unknown".|`undefined` is used to represent "undefined", "not defined", or "value unknown".| +|5. |`null` is a special value that represents "nothing", "empty", or "value unknown".|`undefined` is a special value that represents an undefined value.| +|6. |`let car = null;`|`let data;`| +| |`console.log(car); // Output: null`|`console.log(data); // Output: undefined`| + +::: + +## Conclusion + +In this article, we learned about the data types in JavaScript. We also learned about the type conversion in JavaScript. Understanding data types and type conversion is important for writing efficient and bug-free code. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/non-primitive-data-types/_category_.json b/languages-platforms/javascript/datatypes/non-primitive-data-types/_category_.json new file mode 100644 index 0000000..d09ee00 --- /dev/null +++ b/languages-platforms/javascript/datatypes/non-primitive-data-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Non Primitive Data Types", + "position": 3, + "link": { + "type": "generated-index", + "description": "In JavaScript Non Primitive Data Types (object data types) are used to store complex data types. These are the reference data types. They are called so because they don't store the value directly, they store the reference of the value. The reference is a pointer to a location in memory where the value is stored. Non-primitive data types are used to store complex objects. They are also called reference data types because they refer to the objects. Non-primitive data types are Object, Array, and Function." + } + } \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/non-primitive-data-types/array-js.mdx b/languages-platforms/javascript/datatypes/non-primitive-data-types/array-js.mdx new file mode 100644 index 0000000..46fc94c --- /dev/null +++ b/languages-platforms/javascript/datatypes/non-primitive-data-types/array-js.mdx @@ -0,0 +1,306 @@ +--- +id: array-datatypes-in-javascript +title: Array Data Types in JavaScript +sidebar_label: Array +sidebar_position: 2 +tags: [JavaScript, Data Types, Non-Primitive Data Types, Array, 'Array in JavaScript', 'Array data type', 'Creating arrays in JavaScript', 'Accessing array elements', 'Modifying array elements', 'Adding array elements', 'Deleting array elements', 'Array methods', 'Array properties', 'Array styles', 'Typed arrays', 'Array-like objects', 'Array buffers', 'Array buffer views', 'Array destructuring', 'Array spread operator', Arrays Style, Dense Array, Sparse Array, Typed Arrays, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array] +description: What is the array data type in JavaScript? Learn about the array data type and how to create, access, modify, add, and delete array elements in JavaScript. +--- + +An `Array` is a non-primitive data type in JavaScript. It represents a collection of elements, where each element can be of any data type, including other arrays. + +```mermaid +graph TD; + subgraph "Arrays" + style arrayStyle fill:#FF00FF,color:#333,stroke-width:2px; + arrayStyle --> denseArray["Dense Array"]; + denseArray --> sparseArray["Sparse Array"]; + arrayStyle --> arrayLike["Array-like Objects"]; + arrayLike --> argumentsObject["Arguments Object"]; + end; + subgraph "Typed Arrays" + style typedArrayStyle fill:#FF00FF,color:#333,stroke-width:2px; + typedArrayStyle --> Int8Array["Int8Array"]; + typedArrayStyle --> Uint8Array["Uint8Array"]; + typedArrayStyle --> Uint8ClampedArray["Uint8ClampedArray"]; + typedArrayStyle --> Int16Array["Int16Array"]; + typedArrayStyle --> Uint16Array["Uint16Array"]; + typedArrayStyle --> Int32Array["Int32Array"]; + typedArrayStyle --> Uint32Array["Uint32Array"]; + typedArrayStyle --> Float32Array["Float32Array"]; + typedArrayStyle --> Float64Array["Float64Array"]; + end; + +``` + +## What is an Array in JavaScript? + +In JavaScript, an `Array` is a special type of object that represents a collection of elements. The elements can be of any data type, including other arrays. Arrays are used to store multiple values in a single variable. Each element in an array has a unique index, which is used to access the element. The index starts from `0` and goes up to `length - 1`, where `length` is the number of elements in the array. + + +## Creating Arrays in JavaScript + +You can create an array in JavaScript using the following syntax: + +```js title="Creating Arrays in JavaScript" +let numbers = [1, 2, 3, 4, 5]; +let names = ['John', 'Doe', 'Jane', 'Smith']; +let mixed = [1, 'John', true, null, undefined]; +``` + +In the above examples, we have created arrays of numbers, strings, and mixed data types. + +## Accessing Array Elements + +You can access elements of an array using their index. The index starts from `0` for the first element and goes up to `length - 1` for the last element. + +```js title="Accessing Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +console.log(numbers[0]); // Output: 1 +console.log(numbers[2]); // Output: 3 +console.log(numbers[4]); // Output: 5 +``` + +In the above example, we have accessed the first, third, and fifth elements of the `numbers` array using their indices. + +## Modifying Array Elements + +You can modify elements of an array using their index. + +```js title="Modifying Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +numbers[0] = 10; + +console.log(numbers); // Output: [10, 2, 3, 4, 5] +``` + +In the above example, we have modified the first element of the `numbers` array and changed its value to `10`. + +## Adding Array Elements + +You can add elements to the end of an array using the `push` method. + +```js title="Adding Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +numbers.push(6); + +console.log(numbers); // Output: [1, 2, 3, 4, 5, 6] +``` + +In the above example, we have added the number `6` to the end of the `numbers` array using the `push` method. + +## Deleting Array Elements + +You can delete elements from an array using the `delete` operator or the `splice` method. + +```js title="Deleting Array Elements" +let numbers = [1, 2, 3, 4, 5]; + +delete numbers[2]; + +console.log(numbers); // Output: [1, 2, empty, 4, 5] +``` + +In the above example, we have deleted the third element of the `numbers` array using the `delete` operator. The element is replaced with `empty`, which is a placeholder for the deleted element. + +## Deleting Array Elements using `pop` Method + +You can also delete elements from the end of an array using the `pop` method. + +```js title="Deleting Array Elements using pop Method" +let numbers = [1, 2, 3, 4, 5]; + +numbers.pop(); + +console.log(numbers); // Output: [1, 2, 3, 4] +``` + +In the above example, we have deleted the last element of the `numbers` array using the `pop` method. + +:::info ๐Ÿ“ Note + +## Arrays Style in JavaScript + +There are different styles of arrays in JavaScript: + +### 1. Dense Array + +A dense array is an array in which the elements are stored in contiguous memory locations. It is the most common type of array in JavaScript. + +for example: + +```js title="Dense Array" +let numbers = [1, 2, 3, 4, 5]; +``` + +### 2. Sparse Array + +A sparse array is an array in which the elements are not stored in contiguous memory locations. It contains empty slots, which are placeholders for the missing elements. + +for example: + +```js title="Sparse Array" +let numbers = [1, , 3, , 5]; +``` + +### 3. Array-like Objects + +Array-like objects are objects that have a `length` property and indexed elements, but they are not instances of the `Array` constructor. + +for example: + +```js title="Array-like Objects" +let arrayLike = { + 0: 'a', + 1: 'b', + 2: 'c', + length: 3 +}; +``` + +### 4. Typed Arrays + +Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. They are used to represent raw binary data in memory and are used in various scenarios, such as working with WebGL, file I/O, and networking. + +for example: + +```js title="Typed Arrays" +let buffer = new ArrayBuffer(16); +let int32Array = new Int32Array(buffer); +``` + +## Typed Arrays in JavaScript + +Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. They are used to represent raw binary data in memory and are used in various scenarios, such as working with WebGL, file I/O, and networking. + +The following are the different types of typed arrays available in JavaScript: + +### 1. `Int8Array` + +The `Int8Array` represents an array of 8-bit signed integers. + +for example: + +```js title="Int8Array" +let buffer = new ArrayBuffer(16); +let int8Array = new Int8Array(buffer); +``` + +### 2. `Uint8Array` + +The `Uint8Array` represents an array of 8-bit unsigned integers. + +for example: + +```js title="Uint8Array" +let buffer = new ArrayBuffer(16); +let uint8Array = new Uint8Array(buffer); +``` + +### 3. `Uint8ClampedArray` + +The `Uint8ClampedArray` represents an array of 8-bit unsigned integers clamped to 0-255. + +for example: + +```js title="Uint8ClampedArray" +let buffer = new ArrayBuffer(16); +let uint8ClampedArray = new Uint8ClampedArray(buffer); +``` + +### 4. `Int16Array` + +The `Int16Array` represents an array of 16-bit signed integers. + +for example: + +```js title="Int16Array" +let buffer = new ArrayBuffer(16); +let int16Array = new Int16Array(buffer); +``` + +### 5. `Uint16Array` + +The `Uint16Array` represents an array of 16-bit unsigned integers. + +for example: + +```js title="Uint16Array" +let buffer = new ArrayBuffer(16); +let uint16Array = new Uint16Array(buffer); +``` + +### 6. `Int32Array` + +The `Int32Array` represents an array of 32-bit signed integers. + +for example: + +```js title="Int32Array" +let buffer = new ArrayBuffer(16); +let int32Array = new Int32Array(buffer); +``` + +### 7. `Uint32Array` + +The `Uint32Array` represents an array of 32-bit unsigned integers. + +for example: + +```js title="Uint32Array" +let buffer = new ArrayBuffer(16); +let uint32Array = new Uint32Array(buffer); +``` + +### 8. `Float32Array` + +The `Float32Array` represents an array of 32-bit floating-point numbers. + +for example: + +```js title="Float32Array" +let buffer = new ArrayBuffer(16); +let float32Array = new Float32Array(buffer); +``` + +### 9. `Float64Array` + +The `Float64Array` represents an array of 64-bit floating-point numbers. + +for example: + +```js title="Float64Array" +let buffer = new ArrayBuffer(16); +let float64Array = new Float64Array(buffer); +``` +::: + +--- + +:::tip Tips and Tricks + +1. **Array Literals**: The array literal syntax `[]` is the most common way to create arrays in JavaScript. +2. **Array Elements**: Arrays can contain elements of any data type, including other arrays. +3. **Accessing Array Elements**: You can access array elements using their index, which starts from `0`. +4. **Modifying Array Elements**: You can modify array elements using their index. +5. **Adding Array Elements**: You can add elements to the end of an array using the `push` method. +6. **Deleting Array Elements**: You can delete elements from an array using the `delete` operator or the `splice` method. +7. **Deleting Array Elements using `pop` Method**: You can delete elements from the end of an array using the `pop` method. +8. **Array Styles**: There are different styles of arrays in JavaScript, including dense arrays, sparse arrays, array-like objects, and typed arrays. +9. **Typed Arrays**: Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. +10. **Array Methods**: JavaScript provides various methods for working with arrays, such as `push`, `pop`, `shift`, `unshift`, `splice`, `slice`, `concat`, `join`, `reverse`, `sort`, `indexOf`, `lastIndexOf`, `includes`, `forEach`, `map`, `filter`, `reduce`, and `find`. +11. **Array Properties**: Arrays have various properties, such as `length`, `constructor`, and `prototype`. +12. **Array-like Objects**: Array-like objects are objects that have a `length` property and indexed elements, but they are not instances of the `Array` constructor. +13. **Typed Arrays**: Typed arrays are a set of array-like objects that provide a way to work with binary data in JavaScript. +14. **Array Buffers**: Array buffers are used to represent raw binary data in memory and are used in various scenarios, such as working with WebGL, file I/O, and networking. +15. **Array Buffer Views**: Array buffer views are used to read and write binary data to and from array buffers. +16. **Array Destructuring**: Array destructuring is a convenient way to extract multiple elements from an array and assign them to variables. +17. **Array Spread Operator**: The array spread operator (`...`) is used to expand an array into individual elements. +::: + +## Conclusion + +In this tutorial, you learned about the array data type in JavaScript and how to create, access, modify, add, and delete array elements. You can use arrays to store multiple values in a single variable and perform various operations on the elements of the array. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/non-primitive-data-types/date-js.md b/languages-platforms/javascript/datatypes/non-primitive-data-types/date-js.md new file mode 100644 index 0000000..25bf66d --- /dev/null +++ b/languages-platforms/javascript/datatypes/non-primitive-data-types/date-js.md @@ -0,0 +1,163 @@ +--- +id: date-datatypes-in-javascript +title: Date Datatypes in JavaScript +sidebar_label: Date +sidebar_position: 4 +tags: [JavaScript, Date, Date Datatypes in JavaScript, Date in JavaScript, JavaScript Date, JavaScript Date Datatypes, JavaScript Date Object, JavaScript Date Methods, JavaScript Date Examples, JavaScript Date Tutorial, JavaScript Date and Time, JavaScript Date Format, JavaScript Date Operations, JavaScript Date Functions, JavaScript Date Properties, JavaScript Date Setters, JavaScript Date Getters, JavaScript Date Working with Dates and Times, JavaScript Date Difference, JavaScript Date Add Days, JavaScript Date Add Months, JavaScript Date Add Years, JavaScript Date Add Hours, JavaScript Date Add Minutes, JavaScript Date Add Seconds, JavaScript Date Add Milliseconds, JavaScript Date Add Time, JavaScript Date Format, JavaScript Date Format Examples, JavaScript Date Format Tutorial, JavaScript Date Format Options, JavaScript Date Format Locale, JavaScript Date Format Timezone, JavaScript Date Format Date, JavaScript Date Format Time, JavaScript Date Format Day, JavaScript Date Format Month, JavaScript Date Format Year, JavaScript Date Format Weekday, JavaScript Date Format Week, JavaScript Date Format Hour, JavaScript Date Format Minute, JavaScript Date Format Second, JavaScript Date Format Millisecond, JavaScript Date Format UTC, JavaScript Date Format Local, JavaScript Date Format ISO, JavaScript Date Format Short, JavaScript Date Format Medium, JavaScript Date Format Long, JavaScript Date Format Full, JavaScript Date Format Custom] +description: What is a Date in JavaScript and how to use it to work with dates and times. +--- + +Date is a built-in object in JavaScript that is used to work with dates and times. It is used to represent a date and time in JavaScript. It is used to work with dates and times in JavaScript. + +```mermaid +sequenceDiagram + participant User + participant JavaScriptEngine + participant DateObject + + User->>JavaScriptEngine: Create a new Date object + JavaScriptEngine->>DateObject: Create Date object + + loop Initialization + JavaScriptEngine->>DateObject: Initialize with current date and time + end + + User->>DateObject: Perform operations (e.g., getDate(), getMonth(), etc.) + DateObject-->>JavaScriptEngine: Return result + + loop Update + User->>JavaScriptEngine: Update Date object (e.g., setFullYear()) + JavaScriptEngine->>DateObject: Update Date object + end + + JavaScriptEngine-->>User: Return updated Date object +``` + +## What is a Date in JavaScript? + +A Date object in JavaScript is used to work with dates and times. It is used to represent a date and time in JavaScript. It is used to work with dates and times in JavaScript. + +## Creating a Date Object + +A Date object can be created using the `new` keyword followed by the `Date` constructor. + +```js title="Creating a Date object" +let date = new Date(); +``` + +This will create a new Date object initialized with the current date and time. + +## Date Methods + +The Date object has several methods that can be used to work with dates and times. Some of the most commonly used methods are: + +- `getDate()`: Returns the day of the month (1-31). +- `getMonth()`: Returns the month (0-11). +- `getFullYear()`: Returns the year. +- `getHours()`: Returns the hour (0-23). +- `getMinutes()`: Returns the minutes (0-59). +- `getSeconds()`: Returns the seconds (0-59). +- `getMilliseconds()`: Returns the milliseconds (0-999). +- `getTime()`: Returns the number of milliseconds since January 1, 1970. + +```js title="Using Date methods" +let date = new Date(); +console.log(date.getDate()); // 1-31 +console.log(date.getMonth()); // 0-11 +console.log(date.getFullYear()); // year +console.log(date.getHours()); // 0-23 +console.log(date.getMinutes()); // 0-59 +console.log(date.getSeconds()); // 0-59 +console.log(date.getMilliseconds()); // 0-999 +console.log(date.getTime()); // milliseconds since January 1, 1970 +``` + +```jsx live +function myDate() { + const [date, setDate] = useState(new Date()); + useEffect(() => { + const timerID = setInterval(() => tick(), 1000); + + return function cleanup() { + clearInterval(timerID); + }; + }); + + function tick() { + setDate(new Date()); + } + + return ( +
+

date.getDate(): {date.getDate()}

+

date.getMonth(): {date.getMonth()}

+

date.getFullYear(): {date.getFullYear()}

+

getHours(): {date.getHours()}

+

date.getMinutes(): {date.getMinutes()}

+

date.getSeconds(): {date.getSeconds()}

+

date.getMilliseconds(): {date.getMilliseconds()}

+

date.getTime(): {date.getTime()}

+
+ ); +} +``` + +## Updating a Date Object + +A Date object can be updated using the various `set` methods. + +- `setDate()`: Sets the day of the month (1-31). +- `setMonth()`: Sets the month (0-11). +- `setFullYear()`: Sets the year. +- `setHours()`: Sets the hour (0-23). +- `setMinutes()`: Sets the minutes (0-59). +- `setSeconds()`: Sets the seconds (0-59). +- `setMilliseconds()`: Sets the milliseconds (0-999). +- `setTime()`: Sets the number of milliseconds since January 1, 1970. + +```js title="Updating a Date object" +let date = new Date(); +date.setDate(15); // set the day of the month to 15 +date.setMonth(6); // set the month to July +date.setFullYear(2022); // set the year to 2022 +date.setHours(12); // set the hour to 12 +date.setMinutes(30); // set the minutes to 30 +date.setSeconds(45); // set the seconds to 45 +date.setMilliseconds(500); // set the milliseconds to 500 +date.setTime(1640999405500); // set the date to January 1, 2022 12:30:45.500 PM +``` + +## Working with Dates and Times + +The Date object can be used to work with dates and times in JavaScript. It can be used to perform various operations such as getting and updating date and time, calculating the difference between two dates, formatting dates, and so on. + +```js title="Working with Dates and Times" +let date1 = new Date(); +let date2 = new Date(2022, 6, 15, 12, 30, 0, 0); // July 15, 2022 12:30:00.000 PM + +// calculate the difference between two dates +let diff = date2 - date1; + +// format the date + +let options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}; + +console.log(date1.toLocaleDateString("en-US", options)); // Monday, January 1, 2022 + +// add 10 days to the date + +date1.setDate(date1.getDate() + 10); +``` + +:::info ๐Ÿ“ Note +The Date object in JavaScript uses a zero-based index for months (0-11) and a one-based index for days (1-31). +::: + +## Conclusion + +In this tutorial, we learned about the Date object in JavaScript and how to use it to work with dates and times. We learned how to create a Date object, use its methods to get and update date and time, and how to use it to work with dates and times in JavaScript. diff --git a/languages-platforms/javascript/datatypes/non-primitive-data-types/function-js.mdx b/languages-platforms/javascript/datatypes/non-primitive-data-types/function-js.mdx new file mode 100644 index 0000000..07db605 --- /dev/null +++ b/languages-platforms/javascript/datatypes/non-primitive-data-types/function-js.mdx @@ -0,0 +1,211 @@ +--- +id: function-datatypes-in-javascript +title: Function Datatypes in JavaScript +sidebar_label: Function +sidebar_position: 3 +tags: [JavaScript, Function, Datatypes, JavaScript Tutorial, JavaScript Function, JavaScript Function Datatypes, JavaScript Function, Types of Function, JavaScript Function Types, JavaScript Function Expression, JavaScript Arrow Function, JavaScript IIFE, JavaScript Generator Function, JavaScript Function Parameters, JavaScript Function Return Value, JavaScript Function Definition, JavaScript Function Syntax, JavaScript Function Example, JavaScript Function Tutorial, JavaScript Function Basics, JavaScript Function Introduction, JavaScript Function Guide, JavaScript Function Fundamentals, JavaScript Function Overview, JavaScript Function Concepts, JavaScript Function Explained, JavaScript Function Quick Start, JavaScript Function Learning, JavaScript] +description: What is a function in JavaScript? How to define a function in JavaScript? What are the different ways to define a function in JavaScript? What are the different types of function in JavaScript? Learn all about functions in JavaScript in this guide. +--- + +In JavaScript, a function is a block of code that can be called and executed. It is a reusable piece of code that can be called multiple times. Functions are used to perform a specific task and can be defined using the `function` keyword. + +## Defining a Function + +A function can be defined using the `function` keyword followed by the function name and a pair of parentheses. The function body is enclosed within a pair of curly braces `{}`. + +```js title="Syntax" +function functionName() { + // function body +} +``` + +Here's an example of a simple function that logs a message to the console: + +```js title="Example" +function greet() { + console.log('Hello, World!'); +} + +greet(); // Output: Hello, World! +``` + +## Function Parameters + +A function can accept parameters, which are variables that are passed to the function when it is called. These parameters are used within the function to perform a specific task. + +```js title="Syntax" +function functionName(parameter1, parameter2, ...) { + // function body +} +``` + +Here's an example of a function that accepts a parameter: + +```js title="Example" +function greet(name) { + console.log(`Hello, ${name}!`); +} + +greet('John'); // Output: Hello, John! +greet('Jane'); // Output: Hello, Jane! +``` + +## Function Return Value + +A function can return a value using the `return` statement. The return value can be used by the calling code to perform further operations. + +```js title="Syntax" +function functionName() { + // function body + return value; +} +``` + +Here's an example of a function that returns a value: + +```js title="Example" +function add(a, b) { + return a + b; +} + +let result = add(2, 3); +console.log(result); // Output: 5 +``` + +## Function Expression + +A function can also be defined using a function expression, which is a function that is assigned to a variable. Function expressions can be named or anonymous. + +### Named Function Expression + +A named function expression is a function expression that has a name. The name can be used within the function to refer to itself. + +```js title="Syntax" +let functionName = function() { + // function body +}; +``` + +Here's an example of a named function expression: + +```js title="Example" +let greet = function sayHello() { + console.log('Hello, World!'); +}; + +greet(); // Output: Hello, World! + +// The function name can be used within the function + +sayHello(); // ReferenceError: sayHello is not defined +``` + +### Anonymous Function Expression + +An anonymous function expression is a function expression that does not have a name. It is assigned to a variable and can be called using the variable name. + +```js title="Syntax" +let functionName = function() { + // function body +}; +``` + +Here's an example of an anonymous function expression: + +```js title="Example" +let greet = function() { + console.log('Hello, World!'); +}; + +greet(); // Output: Hello, World! +``` + +## Arrow Function + +An arrow function is a concise way to define a function using the `=>` syntax. It is a shorthand for writing function expressions. + +```js title="Syntax" +let functionName = (parameter1, parameter2, ...) => { + // function body +}; +``` + +Here's an example of an arrow function: + +```js title="Example" +let greet = name => { + console.log(`Hello, ${name}!`); +}; + +greet('John'); // Output: Hello, John! + +// If the function body contains only one statement, the curly braces can be omitted + +let add = (a, b) => a + b; + +let result = add(2, 3); + +console.log(result); // Output: 5 +``` + +## IIFE (Immediately Invoked Function Expression) + +An IIFE is a function that is defined and called immediately. It is used to create a new scope and to avoid polluting the global scope. + +```js title="Syntax" +(function() { + // function body +})(); +``` + +Here's an example of an IIFE: + +```js title="Example" +(function() { + let message = 'Hello, World!'; + console.log(message); +})(); + +// Output: Hello, World! + +console.log(message); // ReferenceError: message is not defined +``` + +## Generator Function + +A generator function is a special type of function that can be paused and resumed. It is defined using the `function*` keyword and the `yield` keyword is used to pause the function. + +```js title="Syntax" +function* functionName() { + // function body +} +``` + +Here's an example of a generator function: + +```js title="Example" +function* count() { + yield 1; + yield 2; + yield 3; +} + +let generator = count(); + +console.log(generator.next().value); // Output: 1 +console.log(generator.next().value); // Output: 2 +console.log(generator.next().value); // Output: 3 +console.log(generator.next().value); // Output: undefined +``` + +:::info ๐Ÿ“ Note +1. **Function Declaration**: A function declaration is hoisted, which means it is available before it is defined. It can be called before it is defined. +2. **Function Expression**: A function expression is not hoisted, which means it is not available before it is defined. It cannot be called before it is defined. +3. **Arrow Function**: An arrow function does not have its own `this`, `arguments`, `super`, or `new.target`. It uses the `this`, `arguments`, `super`, and `new.target` of the enclosing scope. +4. **IIFE**: An IIFE is used to create a new scope and to avoid polluting the global scope. It is defined and called immediately. +5. **Generator Function**: A generator function is a special type of function that can be paused and resumed. It is defined using the `function*` keyword and the `yield` keyword is used to pause the function. +::: + +## Conclusion + +In this tutorial, we learned about functions in JavaScript. We learned how to define a function, how to pass parameters to a function, how to return a value from a function, and the different ways to define a function in JavaScript. We also learned about function expressions, arrow functions, IIFE, and generator functions. Functions are an important concept in JavaScript and are used to perform a specific task. They are reusable and can be called multiple times. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/non-primitive-data-types/object-js.mdx b/languages-platforms/javascript/datatypes/non-primitive-data-types/object-js.mdx new file mode 100644 index 0000000..f79ba6c --- /dev/null +++ b/languages-platforms/javascript/datatypes/non-primitive-data-types/object-js.mdx @@ -0,0 +1,275 @@ +--- +id: object-datatypes-in-javascript +title: Object Data Types in JavaScript +sidebar_label: Object +sidebar_position: 1 +tags: [JavaScript, Data Types, Non-Primitive Data Types, Object, 'Object in JavaScript', 'Object data type', 'Object methods', 'Object properties', 'Object constructor', 'Creating objects in JavaScript', 'Accessing object properties', 'Modifying object properties', 'Adding object properties', 'Deleting object properties'] +description: What is the object data type in JavaScript? Learn about the object data type and how to create, access, modify, add, and delete object properties in JavaScript. +--- + +The `Object` is a non-primitive data type in JavaScript. It represents a collection of key-value pairs, where the keys are strings (or symbols) and the values can be of any data type, including other objects. + +```mermaid +classDiagram + class Object { + Object() + toString(): string + hasOwnProperty(prop: string): boolean + isPrototypeOf(obj: Object): boolean + propertyIsEnumerable(prop: string): boolean + } + + class Function { + Function() + apply(thisArg: any, argsArray?: any[]): any + call(thisArg: any, ...args: any[]): any + bind(thisArg: any, ...args: any[]): any + toString(): string + } + + class Array { + Array() + length: number + concat(...items: ConcatArray[]): T[] + push(...items: T[]): number + pop(): T | undefined + slice(start?: number, end?: number): T[] + splice(start: number, deleteCount?: number): T[] + indexOf(searchElement: T, fromIndex?: number): number + } + + class Date { + Date() + now(): number + toString(): string + getFullYear(): number + getMonth(): number + getDate(): number + getDay(): number + getHours(): number + getMinutes(): number + getSeconds(): number + getMilliseconds(): number + } + + Object <|-- Function + Object <|-- Array + Object <|-- Date + +``` + +## What is Object in JavaScript? + +In JavaScript, an `Object` is a non-primitive data type that represents a collection of key-value pairs. It is used to store various keyed collections and more complex entities. An object can be created using the object literal syntax `{}` or the `Object` constructor. + +## Syntax of Object in JavaScript + +The syntax for creating an object in JavaScript using the object literal syntax is as follows: + +```js title="Object Literal Syntax" +let object = { + key1: value1, + key2: value2, + // ... + keyN: valueN +}; +``` + +In the above syntax: + +- `object` is the name of the object. +- `key1`, `key2`, and `keyN` are the keys of the object. +- `value1`, `value2`, and `valueN` are the values associated with the keys. +- The keys and values are separated by a colon (`:`), and the key-value pairs are separated by commas (`,`). +- The keys can be strings or symbols, and the values can be of any data type, including other objects. +- The object literal syntax `{}` is the most common way to create objects in JavaScript. + +## How to Create Objects in JavaScript? + +You can create an `Object` in JavaScript using the following syntax: + +```js title="Creating Objects in JavaScript" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +console.log(person); // Output: { name: 'John Doe', age: 30, isEmployed: true } +``` + +In the above example, the `person` object is created using the object literal syntax `{}`. It contains three key-value pairs: `name`, `age`, and `isEmployed`. + +## Accessing Object Properties + +You can access the properties of an object using the dot notation (`.`) or the bracket notation (`[]`). + +### Dot Notation + +You can access the properties of an object using the dot notation (`.`) as follows: + +```js title="Accessing Object Properties using Dot Notation" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +console.log(person.name); // Output: John Doe +console.log(person.age); // Output: 30 +console.log(person.isEmployed); // Output: true +``` + +### Bracket Notation + +You can also access the properties of an object using the bracket notation (`[]`) as follows: + +```js title="Accessing Object Properties using Bracket Notation" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +console.log(person['name']); // Output: John Doe +console.log(person['age']); // Output: 30 +console.log(person['isEmployed']); // Output: true +``` + +## Modifying Object Properties + +You can modify the properties of an object using the assignment operator (`=`). + +```js title="Modifying Object Properties" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +person.age = 35; + +console.log(person.age); // Output: 35 +``` + +In the above example, the `age` property of the `person` object is modified from `30` to `35`. + +## Adding Object Properties + +You can add new properties to an object using the assignment operator (`=`). + +```js title="Adding Object Properties" +let person = { + name: 'Ajay Dhangar', + age: 23, + isEmployed: true +}; + +person.city = 'Mandsaur'; + +console.log(person.city); // Output: Mandsaur +``` + +In the above example, the `city` property is added to the `person` object with the value `'Mandsaur'`. + +## Deleting Object Properties + +You can delete properties from an object using the `delete` operator. + +```js title="Deleting Object Properties" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true +}; + +delete person.isEmployed; + +console.log(person); // Output: { name: 'John Doe', age: 30 } +``` + +In the above example, the `isEmployed` property is deleted from the `person` object. + +## What Can an Object Contain? + +An object can contain properties and methods. Properties are key-value pairs, and methods are functions associated with the object. + +```js title="Object Properties and Methods" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true, + greet: function() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +}; + +console.log(person.name); // Output: John Doe +console.log(person.age); // Output: 30 +console.log(person.isEmployed); // Output: true +console.log(person.greet()); // Output: Hello, my name is John Doe and I am 30 years old. +``` + +In the above example, the `person` object contains four properties: `name`, `age`, `isEmployed`, and `greet`. The `greet` property is a method that returns a greeting message using the `name` and `age` properties of the object. + +## Object Methods + +An object can also contain methods, which are functions that are associated with the object. You can define methods as properties of an object. + +```js title="Object Methods" +let person = { + name: 'John Doe', + age: 30, + isEmployed: true, + greet: function() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } +}; + +console.log(person.greet()); // Output: Hello, my name is John Doe and I am 30 years old. +``` + +In the above example, the `greet` method is defined as a property of the `person` object. It returns a greeting message using the `name` and `age` properties of the object. + +## Object Constructor + +You can also create objects using the `Object` constructor. + +```js title="Creating Objects using Object Constructor" +let person = new Object(); + +person.name = 'John Doe'; + +console.log(person.name); // Output: John Doe +``` + +:::info ๐Ÿ“ Note +The object literal syntax `{}` is the preferred way to create objects in JavaScript. The `Object` constructor is rarely used to create objects. + +The object literal syntax is more concise and easier to read than the `Object` constructor. +::: + +:::tip tips and tricks + +**1. Object Literals**: The object literal syntax `{}` is the most common way to create objects in JavaScript. + +**2. Object Properties**: Objects can contain properties and methods. Properties are key-value pairs, and methods are functions associated with the object. + +**3. Accessing Object Properties**: You can access object properties using the dot notation (`.`) or the bracket notation (`[]`). + +**4. Modifying Object Properties**: You can modify object properties using the assignment operator (`=`). + +**5. Adding Object Properties**: You can add new properties to an object using the assignment operator (`=`). + +**6. Deleting Object Properties**: You can delete properties from an object using the `delete` operator. + +**7. Object Methods**: Objects can contain methods, which are functions associated with the object. + +**8. Object Constructor**: You can create objects using the `Object` constructor, but the object literal syntax is preferred. + +::: + + +## Conclusion + +In JavaScript, the `Object` is a non-primitive data type that represents a collection of key-value pairs. You can create objects using the object literal syntax `{}` or the `Object` constructor. Objects can contain properties and methods, and you can access, modify, add, and delete properties of an object using various techniques. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/_category_.json b/languages-platforms/javascript/datatypes/primitive-data-types/_category_.json new file mode 100644 index 0000000..b8d89e8 --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Primitive Data Types", + "position": 2, + "link": { + "type": "generated-index", + "description": "In the JavaScript, Primitive Data Types are immutable and are passed by value. There are 7 primitive data types: string, number, bigint, boolean, undefined, null and symbol." + } + } \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/big-int-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/big-int-js.md new file mode 100644 index 0000000..a450891 --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/big-int-js.md @@ -0,0 +1,82 @@ +--- +id: bigint-in-javascript +title: BigInt Data Types in JavaScript +sidebar_label: BigInt +sidebar_position: 6 +tags: [JavaScript, Data Types, Primitive Data Types, BigInt, 'BigInt in JavaScript', 'BigInt data type'] +description: What is the BigInt data type in JavaScript? Learn about the BigInt data type and how to create BigInt in JavaScript. +--- + +`BigInt` is a primitive data type in JavaScript. It represents an arbitrary-precision integer. It is used to represent integers larger than the maximum safe integer value. + +```mermaid +graph LR; + A(BigInt)-->|Represents an arbitrary-precision integer| B(BigIntValue); +``` + +## What is BigInt in JavaScript? + +In JavaScript, `BigInt` is a primitive data type that represents an arbitrary-precision integer. It is used to represent integers larger than the maximum safe integer value. + +## How to Create BigInt in JavaScript? + +You can create `BigInt` in JavaScript using the following syntax: + +```js title="Creating BigInt in JavaScript" +let bigNumber = 9007199254740991n; // BigInt + +console.log(bigNumber); // Output: 9007199254740991n +``` + +In the above example, the variable `bigNumber` is assigned the value `9007199254740991n`. The `n` at the end of the number indicates that it is a `BigInt`. + +## Checking for BigInt in JavaScript + +You can check if a variable is a `BigInt` using the `typeof` operator. + +```js title="Checking for BigInt in JavaScript" +let bigNumber = 9007199254740991n; + +console.log(typeof bigNumber); // Output: bigint +``` + +In the above example, the `typeof` operator returns `bigint` for the `bigNumber` variable, indicating that it is a `BigInt`. + +## BigInt vs. Number + +| No. | BigInt | Number | +| --- | ------ | ------ | +| 1. | `BigInt` is used to represent integers larger than the maximum safe integer value. | `Number` is used to represent both integer and floating-point numbers. | +| 2. | `BigInt` is suffixed with `n` to indicate that it is a `BigInt`. | `Number` is not suffixed with any character. | +| 3. | `BigInt` is a primitive data type. | `Number` is a primitive data type. | +| 4. | `BigInt` is used to perform arithmetic operations on large integers. | `Number` is used to perform arithmetic operations on numbers. | + +## BigInt Literals + +A `BigInt` literal is created by appending `n` to the end of an integer or by calling the `BigInt()` function. + +```js title="BigInt Literals" +let bigNumber1 = 9007199254740991n; // BigInt literal + +let bigNumber2 = BigInt(9007199254740991); // BigInt literal using BigInt() function +``` + +In the above example, `bigNumber1` and `bigNumber2` are both `BigInt` literals. + +:::info ๐Ÿ“ Note +- The `n` at the end of the number indicates that it is a `BigInt`. You can also create a `BigInt` using the `BigInt()` function. For example: `let bigNumber = BigInt(9007199254740991);`. +- `n` is not a part of the number, it is a part of the syntax to create a `BigInt`. +- You cannot perform arithmetic operations between `BigInt` and other number types. You need to convert the other number types to `BigInt` before performing arithmetic operations. + + ![perform arithmetic operations between BigInt and other number](image.png) + +- `BigInt` is not supported in all browsers. You should check for browser compatibility before using `BigInt`. +- `BigInt` is a new feature in JavaScript and is not supported in older versions of browsers. +- You can use the `typeof` operator to check if a variable is a `BigInt`. + +::: + + +## Conclusion + +In this tutorial, you learned about the `BigInt` data type in JavaScript, how to create `BigInt` in JavaScript, and how to check for `BigInt` in JavaScript. You also learned that `BigInt` is a primitive data type that represents an arbitrary-precision integer and is used to represent integers larger than the maximum safe integer value. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/boolean-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/boolean-js.md new file mode 100644 index 0000000..a423644 --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/boolean-js.md @@ -0,0 +1,188 @@ +--- +id: boolean-in-javascript +title: Boolean Data Types in JavaScript +sidebar_label: Boolean +sidebar_position: 3 +tags: [JavaScript, Data Types, Primitive Data Types, Boolean, 'Boolean Data Type', 'Boolean Values', 'Boolean Methods', 'Truthy and Falsy'] +description: What is the boolean data type in JavaScript? Learn about the boolean data type in JavaScript, including how to create a boolean, boolean values, and boolean methods. +--- + +Booleans are a primitive data type in JavaScript. They are used to represent logical values. JavaScript uses the `Boolean` object to represent `true` or `false`. + +```mermaid +graph TD; + A(Boolean)-->|Logical Value| B(true); + A(Boolean)-->|Logical Value| C(false); +``` + +## What is a Boolean in JavaScript? + +In JavaScript, booleans are used to represent logical values. JavaScript uses the `Boolean` object to represent `true` or `false`. + +## How to Create a Boolean in JavaScript? + +You can create a boolean in JavaScript using the following syntax: + +```js title="Creating a Boolean in JavaScript" +let isTrue = true; +let isFalse = false; +``` + +In the above example, `isTrue` and `isFalse` are booleans. + +## Boolean Values + +The boolean data type has only two possible values: `true` and `false`. For example: + +```js title="Boolean Values" +let isTrue = true; +let isFalse = false; +``` + +## Boolean Methods + +The `Boolean` object has several methods that are used to perform operations on boolean values. For example: + +```js title="Boolean Methods" +let isTrue = true; +let isFalse = false; + +console.log(isTrue.toString()); // Output: "true" +console.log(isFalse.valueOf()); // Output: false +``` + +In the above example, the `toString()` method is used to convert a boolean to a string, and the `valueOf()` method is used to return the primitive value of a boolean. + +:::info ๐Ÿ“ Note +The `Boolean` object is a wrapper for a boolean value. It is rarely used in practice, as booleans can be created directly without using the `Boolean` object. + +The `Boolean` object is not a constructor. It does not have a `new` operator. It is a function that converts a value to a boolean. + +The `Boolean` object has a single property: `prototype`. It is the prototype for the `Boolean` object. + +for example: + +```js title="Boolean Object" +let isTrue = true; +let isFalse = false; + +console.log(Boolean(isTrue)); // Output: true +console.log(Boolean(isFalse)); // Output: false +``` + +In the above example, the `Boolean` object is used to convert a value to a boolean. + +**1. What is truthy and falsy in JavaScript?** + +In JavaScript, a value is considered "falsy" if it converts to `false` when evaluated in a boolean context. The following values are considered "falsy" in JavaScript: + +- `false` +- `0` +- `""` (empty string) +- `null` +- `undefined` +- `NaN` (Not a Number) +- `document.all` (an object that is present in Internet Explorer) + +All other values are considered "truthy" in JavaScript. + +For example: + +```js title="Truthy and Falsy Values" +let isTrue = true; +let isFalse = false; + +console.log(Boolean(isTrue)); // Output: true +console.log(Boolean(isFalse)); // Output: false +console.log(Boolean(0)); // Output: false +console.log(Boolean("")); // Output: false +console.log(Boolean(null)); // Output: false +console.log(Boolean(undefined)); // Output: false +console.log(Boolean(NaN)); // Output: false +console.log(Boolean(document.all)); // Output: false +``` + +In the above example, the `Boolean` object is used to convert values to booleans. The values `0`, `""`, `null`, `undefined`, `NaN`, and `document.all` are considered "falsy" in JavaScript. + +**2. Difference between truthy and falsy** + +The difference between truthy and falsy is that truthy values are considered `true` when evaluated in a boolean context, while falsy values are considered `false` when evaluated in a boolean context. + +For example: + +**Truthy Values** + +- `true`: The boolean value `true` is considered "truthy" in JavaScript. +- `1`: The number `1` is considered "truthy" in JavaScript. +- `"hello"`: The string `"hello"` is considered "truthy" in JavaScript. +- `[]` (empty array): An empty array is considered "truthy" in JavaScript. +- `{}` (empty object): An empty object is considered "truthy" in JavaScript. +- `function() {}` (empty function): An empty function is considered "truthy" in JavaScript. +- `new Date()`: A new date is considered "truthy" in JavaScript. +- `Infinity`: The value `Infinity` is considered "truthy" in JavaScript. +- `-Infinity`: The value `-Infinity` is considered "truthy" in JavaScript. +- `3.14`: The number `3.14` is considered "truthy" in JavaScript. + +**Falsy Values** + +- `false`: The boolean value `false` is considered "falsy" in JavaScript. +- `0`: The number `0` is considered "falsy" in JavaScript. +- `""` (empty string): An empty string is considered "falsy" in JavaScript. +- `null`: The value `null` is considered "falsy" in JavaScript. +- `undefined`: The value `undefined` is considered "falsy" in JavaScript. +- `NaN`: The value `NaN` is considered "falsy" in JavaScript. +- `0n`: The bigint value `0n` is considered "falsy" in JavaScript. +- `-0`: The number `-0` is considered "falsy" in JavaScript. + + +for example: + +```js title="Truthy Values" +let isTrue = true; +const num = 1; +const str = "hello"; +const arr = []; +const obj = {}; +const func = function() {}; +const date = new Date(); +const inf = Infinity; +const ninf = -Infinity; +const pi = 3.14; + +console.log(Boolean(isTrue)); // Output: true +console.log(Boolean(num)); // Output: true +console.log(Boolean(str)); // Output: true +console.log(Boolean(arr)); // Output: true +console.log(Boolean(obj)); // Output: true +console.log(Boolean(func)); // Output: true +console.log(Boolean(date)); // Output: true +console.log(Boolean(inf)); // Output: true +console.log(Boolean(ninf)); // Output: true +console.log(Boolean(pi)); // Output: true +``` + +```js title="Falsy Values" +let isFalse = false; +const zero = 0; +const emptyStr = ""; +const nul = null; +const undef = undefined; +const nan = NaN; +const bigZero = 0n; +const negZero = -0; + +console.log(Boolean(isFalse)); // Output: false +console.log(Boolean(zero)); // Output: false +console.log(Boolean(emptyStr)); // Output: false +console.log(Boolean(nul)); // Output: false +console.log(Boolean(undef)); // Output: false +console.log(Boolean(nan)); // Output: false +console.log(Boolean(bigZero)); // Output: false +console.log(Boolean(negZero)); // Output: false +``` + +::: + +## Conclusion + +In this tutorial, you learned about the boolean data type in JavaScript, including how to create a boolean, boolean values, and boolean methods. You also learned about the `Boolean` object and its methods. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/image.png b/languages-platforms/javascript/datatypes/primitive-data-types/image.png new file mode 100644 index 0000000..56db1ae Binary files /dev/null and b/languages-platforms/javascript/datatypes/primitive-data-types/image.png differ diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/null-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/null-js.md new file mode 100644 index 0000000..d66d878 --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/null-js.md @@ -0,0 +1,67 @@ +--- +id: null-in-javascript +title: Null Data Types in JavaScript +sidebar_label: "Null" +sidebar_position: 5 +tags: [JavaScript, Data Types, Primitive Data Types, 'Null', 'null data type', 'null in JavaScript'] +description: What is the null data type in JavaScript? Learn about the null data type and how to create null in JavaScript. +--- + +`null` is a primitive data type in JavaScript. It represents a null value. It is used to represent an empty value or no value at all. + +```mermaid +graph LR; + A(Null)-->|Represents a null value| B(NullValue); +``` + +## What is Null in JavaScript? + +In JavaScript, `null` is a primitive data type that represents a null value. It is used to represent an empty value or no value at all. + +## How to Create Null in JavaScript? + +You can create `null` in JavaScript using the following syntax: + +```js title="Creating Null in JavaScript" +let data = null; + +console.log(data); // Output: null +``` + +In the above example, the variable `data` is assigned the value `null`. When you log the value of `data`, it will output `null`. + +## Checking for Null in JavaScript + +You can check if a variable is `null` using the `typeof` operator or by comparing the variable to `null`. + +```js title="Checking for Null in JavaScript" +let data = null; + +console.log(typeof data); // Output: object + +if (data === null) { + console.log('The variable is null'); +} else { + console.log('The variable is not null'); +} +``` + +In the above example, the `typeof` operator returns `object` for the `data` variable, and the comparison `data === null` returns `true`, indicating that the variable is `null`. + + +:::info ๐Ÿ“Note +In JavaScript, `null` is of type `object`. This is a bug in the language that has been kept for compatibility reasons. + +## Null vs. Undefined + +`null` and `undefined` are both used to represent the absence of a value in JavaScript. However, they are not the same. + +- `null` is a primitive data type that represents a null value. It is often used to explicitly set a variable to have no value. + +- `undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +::: + +## Conclusion + +In this article, you learned about the `null` data type in JavaScript, how to create `null` in JavaScript, and how to check for `null` in JavaScript. You also learned that `null` is a primitive data type that represents a null value and is used to represent an empty value or no value at all. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/number-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/number-js.md new file mode 100644 index 0000000..e8721c3 --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/number-js.md @@ -0,0 +1,122 @@ +--- +id: number-datatypes-in-javascript +title: Number Data Types in JavaScript +sidebar_label: Number +sidebar_position: 1 +tags: [JavaScript, Data Types, Primitive Data Types, Number, Integer, Floating-Point Number, NaN, Infinity, BigInt, 'Number.MAX_VALUE', 'Number.MIN_VALUE', 'Number.EPSILON', 'Number.POSITIVE_INFINITY', 'Number.NEGATIVE_INFINITY', 'Number.NaN'] +description: What is the number data type in JavaScript? Learn about the number data type in JavaScript, including integers, floating-point numbers, NaN, Infinity, and BigInt. +--- + +Numbers are a primitive data type in JavaScript. They are used to represent numeric values. JavaScript uses the `Number` object to represent both integer and floating-point numbers. + +```mermaid +graph TD; + A(Number)-->|Integer| B(1, 2, 3, etc.); + A(Number)-->|Float| C(1.1, 2.2, 3.3, etc.); + A(Number)-->|NaN| D(Not a Number); + A(Number)-->|Infinity| E(Positive Infinity, Negative Infinity); + A(Number)-->|BigInt| F(9007199254740991n); + +``` + +## What is a Number in JavaScript? + +In JavaScript, numbers are used to represent numeric values. JavaScript uses the `Number` object to represent both integer and floating-point numbers. + +## How to Create a Number in JavaScript? + +You can create a number in JavaScript using the following syntax: + +```js title="Creating a Number in JavaScript" +let count = 100; // Integer +let price = 99.99; // Floating-point number +``` + +In the above example, `count` is an integer, and `price` is a floating-point number. + +## Integer + +An integer is a whole number, positive or negative, without decimals, of unlimited length. For example: + +```js title="Integer" +let count = 100; +let temperature = -10; +``` + +## Floating-Point Number + +A floating-point number is a number with a decimal point or an exponent. For example: + +```js title="Floating-Point Number" +let price = 99.99; +let pi = 3.14; +``` + +## NaN (Not a Number) + +`NaN` is a special value that represents "Not-a-Number". It indicates that a value is not a legal number. For example: + +```js title="NaN" +let result = 100 / "Apple"; +console.log(result); // Output: NaN +``` + +## Infinity + +`Infinity` is a special value that represents positive infinity. It is displayed when a number exceeds the upper limit of the floating-point numbers. For example: + +```js title="Infinity" +let max = Number.MAX_VALUE; +let infinity = max * 2; +console.log(infinity); // Output: Infinity +``` + +## BigInt + +The `bigint` data type is used to represent whole numbers larger than `2^53 - 1`. It is a new feature in JavaScript and is not supported in all browsers. For example: + +```js title="BigInt" +let value = 9007199254740991n; +``` + +:::info ๐Ÿ“ Note +- The `n` at the end of the number indicates that it is a `bigint`. You can also create a `bigint` using the `BigInt()` function. For example: `let value = BigInt(9007199254740991);`. +- `n` is not a part of the number, it is a part of the syntax to create a `bigint`. +- You cannot perform arithmetic operations between `bigint` and other number types. You need to convert the other number types to `bigint` before performing arithmetic operations. +- infinity is used to represent positive infinity, and `-Infinity` is used to represent negative infinity. +- `NaN` is used to represent "Not-a-Number". It indicates that a value is not a legal number. +- `Number.MAX_VALUE` is the largest positive finite value representable in JavaScript. +- `Number.MIN_VALUE` is the smallest positive value representable in JavaScript. +- `Number.EPSILON` is the smallest interval between two representable numbers. +- `Number.POSITIVE_INFINITY` is the positive infinity value. +::: + +:::tip tipes and tricks +1. Integers: + - An integer is a whole number, positive or negative, without decimals, of unlimited length. + - For example: `let count = 100;`, `let temperature = -10;` + - Output: `100`, `-10` +2. Floating-Point Numbers: + - A floating-point number is a number with a decimal point or an exponent. + - For example: `let price = 99.99;`, `let pi = 3.14;` + - Output: `99.99`, `3.14` +3. NaN (Not a Number): + - `NaN` is a special value that represents "Not-a-Number". + - It indicates that a value is not a legal number. + - For example: `let result = 100 / "Apple";` + - Output: `NaN` +4. Infinity: + - `Infinity` is a special value that represents positive infinity. + - It is displayed when a number exceeds the upper limit of the floating-point numbers. + - For example: `let max = Number.MAX_VALUE;`, `let infinity = max * 2;` + - Output: `Infinity` +5. BigInt: + - The `bigint` data type is used to represent whole numbers larger than `2^53 - 1`. + - It is a new feature in JavaScript and is not supported in all browsers. + - For example: `let value = 9007199254740991n;` + - Output: `9007199254740991n` +::: + +## Conclusion + +In this article, you learned about the number data type in JavaScript and how to use it. You also learned about integers, floating-point numbers, `NaN`, `Infinity`, and `BigInt`. You can use these data types to represent numeric values in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/strings-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/strings-js.md new file mode 100644 index 0000000..f0d3622 --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/strings-js.md @@ -0,0 +1,203 @@ +--- +id: string-datatypes-in-javascript +title: String Data Types in JavaScript +sidebar_label: String +sidebar_position: 2 +tags: [JavaScript, Data Types, Primitive Data Types, String, 'String Data Type', 'String Length', 'String Methods', 'Template Literals', 'Escape Characters', 'String Concatenation', 'String Interpolation'] +description: What is the string data type in JavaScript? Learn about the string data type in JavaScript, including how to create a string, escape characters, string length, string methods, and template literals. +--- + +Strings are a primitive data type in JavaScript. They are used to represent text. JavaScript uses the `String` object to represent a sequence of characters. + +```mermaid +graph TD; + A(String)-->|Text| B("Hello World!"); + A(String)-->|Text| C("John Doe"); +``` + +## What is a String in JavaScript? + +In JavaScript, strings are used to represent text. JavaScript uses the `String` object to represent a sequence of characters. + +## How to Create a String in JavaScript? + +You can create a string in JavaScript using the following syntax: + +```js title="Creating a String in JavaScript" +let name = "Ajay Dhangar"; // Double quotes +let message = 'Hello World!'; // Single quotes +``` + +In the above example, `name` and `message` are strings. + +## Double Quotes vs. Single Quotes + +| No. | Double Quotes | Single Quotes | +| --- | -------------- | -------------- | +| 1. | "Hello World!" | 'Hello World!' | +| 2. | "John Doe" | 'John Doe' | + +## Escape Characters + +In JavaScript, you can use the backslash (`\`) to escape characters in a string. The following table lists the escape characters in JavaScript: + +| Escape Character | Description | +| ---------------- | ---------------------------------------- | +| `\'` | Single quote | +| `\"` | Double quote | +| `\\` | Backslash | +| `\n` | New line | +| `\r` | Carriage return | +| `\t` | Tab | +| `\b` | Backspace | +| `\f` | Form feed | +| `\v` | Vertical tab | + +## String Length + +In JavaScript, you can use the `length` property to get the length of a string. For example: + +```js title="String Length" +let name = "John Doe"; + +console.log(name.length); // Output: 8 +``` + +In the above example, the length of the string `name` is `8`. + +## String Methods + +JavaScript provides several methods to work with strings. Some of the most commonly used string methods are: + +- `concat()`: Concatenates two or more strings. For example: + + ```js title="concat()" + let firstName = "John"; + let lastName = "Doe"; + + let fullName = firstName.concat(" ", lastName); + console.log(fullName); // Output: John Doe + ``` + +- `toUpperCase()`: Converts a string to uppercase. For example: + + ```js title="toUpperCase()" + let name = "John Doe"; + + console.log(name.toUpperCase()); // Output: JOHN DOE + ``` + +- `toLowerCase()`: Converts a string to lowercase. For example: + + ```js title="toLowerCase()" + let name = "John Doe"; + + console.log(name.toLowerCase()); // Output: john doe + ``` + +- `charAt()`: Returns the character at a specified index. For example: + + ```js title="charAt()" + let name = "John Doe"; + + console.log(name.charAt(0)); // Output: J + ``` + +- `indexOf()`: Returns the index of the first occurrence of a specified value. For example: + + ```js title="indexOf()" + let name = "John Doe"; + + console.log(name.indexOf("Doe")); // Output: 5 + ``` + +- `lastIndexOf()`: Returns the index of the last occurrence of a specified value. For example: + ```js title="lastIndexOf()" + let name = "John Doe"; + + console.log(name.lastIndexOf("Doe")); // Output: 5 + ``` + +- `includes()`: Returns `true` if a string contains a specified value, otherwise `false`. For example: + + ```js title="includes()" + let name = "John Doe"; + + console.log(name.includes("Doe")); // Output: true + ``` + +- `startsWith()`: Returns `true` if a string starts with a specified value, otherwise `false`. For example: + + ```js title="startsWith()" + let name = "John Doe"; + console.log(name.startsWith("John")); // Output: true + ``` + +- `endsWith()`: Returns `true` if a string ends with a specified value, otherwise `false`. For example: + + ```js title="endsWith()" + let name = "John Doe"; + console.log(name.endsWith("Doe")); // Output: true + ``` + +- `slice()`: Extracts a part of a string and returns a new string. For example: + + ```js title="slice()" + let name = "John Doe"; + console.log(name.slice(5)); // Output: Doe + ``` + +- `substring()`: Extracts a part of a string and returns a new string. For example: + + ```js title="substring()" + let name = "John Doe"; + console.log(name.substring(5)); // Output: Doe + ``` + +- `substr()`: Extracts a part of a string and returns a new string. For example: + + ```js title="substr()" + let name = "John Doe"; + console.log(name.substr(5)); // Output: Doe + ``` + +- `replace()`: Replaces a specified value with another value in a string. For example: + + ```js title="replace()" + let name = "John Doe"; + console.log(name.replace("Doe", "Smith")); // Output: John Smith + ``` + +- `split()`: Splits a string into an array of substrings. For example: + + ```js title="split()" + let name = "John Doe"; + console.log(name.split(" ")); // Output: ["John", "Doe"] + ``` + +- `trim()`: Removes whitespace from both ends of a string. For example: + + ```js title="trim()" + let name = " John Doe "; + console.log(name.trim()); // Output: John Doe + ``` + +## Template Literals + +Template literals are string literals that allow embedded expressions. You can use multi-line strings and string interpolation features with template literals. Template literals are enclosed by the backtick (\`) character. + +```js {2} title="Template Literals" +let name = "John Doe"; +let message = `Hello, ${name}!`; // String interpolation using template literals +console.log(message); // Output: Hello, John Doe! +``` + +In the above example, the `${name}` is a placeholder that is replaced by the value of the `name` variable. + +:::info ๐Ÿ“ Note +Template literals are a new feature in ECMAScript 6 (ES6). +::: + +## Conclusion + +In this tutorial, you learned about the string data type in JavaScript and how to use it. You also learned about escape characters, string length, and string methods. You can use strings to represent text in JavaScript. diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/symbol-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/symbol-js.md new file mode 100644 index 0000000..fd435fd --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/symbol-js.md @@ -0,0 +1,77 @@ +--- +id: symbol-in-javascript +title: Symbol Data Types in JavaScript +sidebar_label: Symbol +sidebar_position: 7 +tags: [JavaScript, Data Types, Primitive Data Types, Symbol, 'Symbol in JavaScript', 'Symbol data type'] +description: What is the symbol data type in JavaScript? Learn about the symbol data type and how to create symbols in JavaScript. +--- + +`Symbol` is a primitive data type in JavaScript. It represents a unique and immutable value. It is used to create unique identifiers for object properties. + +```mermaid +graph LR; + A(Symbol)-->|Represents a unique and immutable value| B(SymbolValue); +``` + +## What is Symbol in JavaScript? + +In JavaScript, `Symbol` is a primitive data type that represents a unique and immutable value. It is used to create unique identifiers for object properties. + +## How to Create Symbols in JavaScript? + +You can create `Symbol` in JavaScript using the following syntax: + +```js title="Creating Symbols in JavaScript" +let id = Symbol('id'); + +console.log(id); // Output: Symbol(id) +``` + +In the above example, the variable `id` is assigned the value `Symbol('id')`. The string `'id'` is used as a description for the symbol, which can be useful for debugging. + +## Checking for Symbols in JavaScript + +You can check if a variable is a `Symbol` using the `typeof` operator. + +```js title="Checking for Symbols in JavaScript" +let id = Symbol('id'); + +console.log(typeof id); // Output: symbol +``` + +In the above example, the `typeof` operator returns `symbol` for the `id` variable, indicating that it is a `Symbol`. + +## Symbol Descriptions + +When creating a `Symbol`, you can provide an optional description that can be used for debugging purposes. + +```js title="Symbol Descriptions" +let id = Symbol('id'); + +console.log(id.description); // Output: id +``` + +In the above example, the `description` property of the `id` symbol returns the string `'id'`, which was provided as a description when creating the symbol. + +## Unique Identifiers + +Symbols are unique and immutable. Even if you create multiple symbols with the same description, they are different values. + +```js title="Unique Identifiers" +let id1 = Symbol('id'); + +let id2 = Symbol('id'); + +console.log(id1 === id2); // Output: false +``` + +In the above example, `id1` and `id2` are both symbols with the same description, but they are different values. + +:::info ๐Ÿ“Note +The description of a `Symbol` is not used in any operations. It is purely a human-readable label for debugging purposes. +::: + +## Conclusion + +In this tutorial, you learned about the `Symbol` data type in JavaScript and how to create symbols. You also learned how to check for symbols and use symbol descriptions. Symbols are useful for creating unique identifiers for object properties and are often used in advanced JavaScript programming. \ No newline at end of file diff --git a/languages-platforms/javascript/datatypes/primitive-data-types/undefined-js.md b/languages-platforms/javascript/datatypes/primitive-data-types/undefined-js.md new file mode 100644 index 0000000..21b42af --- /dev/null +++ b/languages-platforms/javascript/datatypes/primitive-data-types/undefined-js.md @@ -0,0 +1,182 @@ +--- +id: undefined-in-javascript +title: Undefined Data Types in JavaScript +sidebar_label: Undefined +sidebar_position: 4 +tags: [JavaScript, Data Types, Primitive Data Types, Undefined] +description: What is the undefined data type in JavaScript? Learn about the undefined data type and how to create undefined in JavaScript. +--- + + +`undefined` is a primitive data type in JavaScript. It represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +```mermaid +flowchart TD + subgraph Undefined Data Types + Undefined -->|Represents the absence of a value| UndefinedValue + end + + classDef undefinedClass fill:#f9f,stroke:#333,stroke-width:2px; + class UndefinedValue undefinedClass; + + classDef highlight fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class UndefinedValue highlight; + + classDef visibleClass fill:#fff,stroke:#333,stroke-width:2px; + class UndefinedValue visibleClass; + + classDef arrowClass fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class arrow arrowClass; + + classDef hidden invisible; + + class UndefinedValue,undefinedClass visibleClass; + + UndefinedValue -->|Initialize a variable without assigning a value| Value; + Value -->|Use the variable without assigning a value| DisplayValue; + DisplayValue -->|Displays 'undefined'| DisplayUndefined; + DisplayUndefined -->|Output to the console or other output devices| OutputUndefined; + +``` + +## What is Undefined in JavaScript? + +In JavaScript, `undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +## How to Create Undefined in JavaScript? + +You can create `undefined` in JavaScript using the following syntax: + +```js title="Creating Undefined in JavaScript" +let data; + +console.log(data); // Output: undefined +``` + +In the above example, the variable `data` is declared but not assigned a value. When you log the value of `data`, it will output `undefined`. + +## Checking for Undefined in JavaScript + +You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. + +### Using the `typeof` Operator + +You can use the `typeof` operator to check if a variable is `undefined`: + +```js title="Using the typeof Operator to Check for Undefined" +let data; + +console.log(typeof data === 'undefined'); // Output: true +``` + +### Comparing to `undefined` + +You can also compare a variable to `undefined` to check if it is `undefined`: + +```js title="Comparing to Undefined to Check for Undefined" +let data; + +console.log(data === undefined); // Output: true +``` + +## Undefined vs. Null + +`undefined` and `null` are both used to represent the absence of a value in JavaScript. However, they are not the same. + +`undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. + +`null` is an object that represents the absence of a value. It is often used to explicitly set a variable to have no value. + +:::info ๐Ÿ“ Note +In JavaScript, `null` is of type `object`. This is a bug in the language that has been kept for compatibility reasons. + +You can check if a variable is `null` using the `typeof` operator or by comparing the variable to `null`. + +**1. Difference bitween `undefined` and `null`** + +```mermaid +flowchart TD + subgraph Undefined vs. Null + Undefined -->|Represents the absence of a value| UndefinedValue + Null -->|Represents the absence of a value| NullValue + end + + classDef undefinedClass fill:#f9f,stroke:#333,stroke-width:2px; + class UndefinedValue undefinedClass; + + classDef nullClass fill:#f9f,stroke:#333,stroke-width:2px; + class NullValue nullClass; + + classDef highlight fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class UndefinedValue highlight; + class NullValue highlight; + + classDef visibleClass fill:#fff,stroke:#333,stroke-width:2px; + class UndefinedValue,NullValue visibleClass; + + classDef arrowClass fill:#f9f,stroke:#333,stroke-width:2px,stroke-dasharray: 5, 5; + class arrow arrowClass; + + classDef hidden invisible; + + class UndefinedValue,undefinedClass visibleClass; + class NullValue,nullClass visibleClass; + + UndefinedValue -->|Initialize a variable without assigning a value| Value; + Value -->|Use the variable without assigning a value| DisplayValue; + DisplayValue -->|Displays 'undefined'| DisplayUndefined; + DisplayUndefined -->|Output to the console or other output devices| OutputUndefined; + + NullValue -->|Initialize a variable with a null value| Value; + Value -->|Use the variable with a null value| DisplayValue; + DisplayValue -->|Displays 'null'| DisplayNull; + DisplayNull -->|Output to the console or other output devices| OutputNull; +``` +::: + +:::tip tips and tricks +**Why use undefined?** + +`undefined` is used to represent the absence of a value. It is often used to check if a variable has been assigned a value or not. For example, you can use `undefined` to check if a function argument has been passed or not. + +**What means undefined?** + +`undefined` means that a variable has been declared, but has not been assigned a value. It is a primitive data type that represents an undefined value. + +**Why JavaScript has undefined?** + +JavaScript has `undefined` to represent the absence of a value. It is often used to check if a variable has been assigned a value or not. + +**Assume that a variable is undefined?** + +If a variable is `undefined`, it means that it has been declared, but has not been assigned a value. You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. + +**How to play with undefined?** + +You can create `undefined` in JavaScript by declaring a variable without assigning a value to it. You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. + +for example: + +```js title="Creating Undefined in JavaScript" +let data; + +console.log(data); // Output: undefined +``` + +```js title="Using the typeof Operator to Check for Undefined" +let data; + +console.log(typeof data === 'undefined'); // Output: true +``` + +```js title="Comparing to Undefined to Check for Undefined" +let data; + +console.log(data === undefined); // Output: true +``` +::: + + +## Conclusion + +In JavaScript, `undefined` is a primitive data type that represents an undefined value. If a variable has been declared, but has not been assigned a value, it is of type `undefined`. You can create `undefined` in JavaScript by declaring a variable without assigning a value to it. You can check if a variable is `undefined` using the `typeof` operator or by comparing the variable to `undefined`. \ No newline at end of file diff --git a/languages-platforms/javascript/debugging-js.md b/languages-platforms/javascript/debugging-js.md new file mode 100644 index 0000000..c161fce --- /dev/null +++ b/languages-platforms/javascript/debugging-js.md @@ -0,0 +1,162 @@ +--- +id: debugging-js +title: Debugging in JavaScript +sidebar_label: Debugging +sidebar_position: 39 +tags: + [ + JavaScript, + Debugging, + Console, + Breakpoints, + Sources, + Call Stack, + Watch, + Scope, + Network, + Performance, + Memory, + Profiling, + Code Coverage, + Chrome DevTools, + Error Messages, + Code Review, + Debugger Statement, + Debugging Techniques, + ] +description: "In this tutorial, you will learn how to debug JavaScript code in the browser using the Chrome DevTools. We will cover the basics of debugging, including breakpoints, console, sources, call stack, watch, scope, network, performance, memory, profiling, and code coverage." +--- + +Debugging is the process of finding and fixing errors in your code. It is an essential skill for developers to master, as it helps you identify and resolve issues quickly and efficiently. In this tutorial, you will learn how to debug JavaScript code in the browser using the Chrome DevTools. We will cover the basics of debugging, including breakpoints, console, sources, call stack, watch, scope, network, performance, memory, profiling, and code coverage. + +## Common Debugging Techniques + +Here are some common debugging techniques that you can use to debug JavaScript code: + +- **Breakpoints**: Pause the execution of your code at a specific line to inspect the state of your application. +- **Console**: Log messages to the console to track the flow of your code and inspect variables. +- **Sources**: View and edit the source code of your application. +- **Call Stack**: View the sequence of function calls that led to the current point in your code. +- **Watch**: Monitor the value of variables in real-time. +- **Scope**: Inspect the variables in the current scope. +- **Network**: Monitor network requests made by your application. +- **Performance**: Analyze the performance of your application. +- **Memory**: Inspect the memory usage of your application. +- **Profiling**: Profile the performance of your application. +- **Code Coverage**: Measure how much of your code is executed during a test. +- **Debugger Statement**: Use the `debugger` statement to pause the execution of your code. +- **Error Messages**: Read error messages in the console to identify issues in your code. +- **Code Review**: Review your code with a colleague to get a fresh perspective. + +## Debugging with Chrome DevTools + +Chrome DevTools is a set of web developer tools built into the Google Chrome browser. It provides a rich set of debugging tools that you can use to inspect and debug your web applications. To open Chrome DevTools, right-click on a web page and select "Inspect" or press `Ctrl+Shift+I` (Windows/Linux) or `Cmd+Option+I` (Mac). + +### Breakpoints + +Breakpoints allow you to pause the execution of your code at a specific line to inspect the state of your application. To set a breakpoint, click on the line number in the source code panel. When the code reaches the breakpoint, it will pause, and you can inspect the variables and step through the code using the controls in the debugger. + +![Breakpoints in Chrome DevTools](./img/breakpoints.gif) + +### Console + +The console is a powerful tool for logging messages to track the flow of your code and inspect variables. You can log messages using `console.log()`, `console.error()`, `console.warn()`, `console.info()`, and `console.debug()`. You can also evaluate expressions in the console and interact with the page using JavaScript. + +```javascript title="Console Logging" +console.log("Hello, World!"); +console.error("An error occurred!"); +console.warn("Warning: This is a warning!"); +console.info("Information: This is an information message!"); +console.debug("Debug: This is a debug message!"); +``` + +### Sources + +The sources panel allows you to view and edit the source code of your application. You can set breakpoints, step through the code, and inspect variables in the debugger. You can also search for files, navigate the call stack, and view the network requests made by your application. + +![Sources in Chrome DevTools](./img/source.gif) + +### Call Stack + +The call stack panel shows the sequence of function calls that led to the current point in your code. It helps you understand the flow of your code and identify where an error occurred. You can navigate the call stack, inspect the variables in each function, and step through the code using the controls in the debugger. + +![Call Stack in Chrome DevTools](./img/call-stack.gif) + +### Watch + +The watch panel allows you to monitor the value of variables in real-time. You can add variables to the watch list and see their values update as you step through the code. This is useful for tracking the state of your application and identifying issues in your code. + +### Scope + +The scope panel allows you to inspect the variables in the current scope. You can view the local, closure, and global variables, as well as the `this` context. This helps you understand the state of your application and debug issues related to variable scoping. + +### Network + +The network panel allows you to monitor the network requests made by your application. You can view the request and response headers, payloads, and timing information. This helps you identify performance issues, debug network-related errors, and optimize the performance of your application. + +### Performance + +The performance panel allows you to analyze the performance of your application. You can record performance profiles, analyze CPU and memory usage, and identify performance bottlenecks. This helps you optimize the performance of your application and deliver a better user experience. + +### Memory + +The memory panel allows you to inspect the memory usage of your application. You can take heap snapshots, analyze memory allocations, and identify memory leaks. This helps you optimize the memory usage of your application and prevent memory-related issues. + +### Profiling + +The profiling panel allows you to profile the performance of your application. You can record CPU profiles, analyze JavaScript execution, and identify performance bottlenecks. This helps you optimize the performance of your application and deliver a better user experience. + +### Code Coverage + +The code coverage panel allows you to measure how much of your code is executed during a test. You can record code coverage profiles, analyze the coverage of your code, and identify unused code. This helps you ensure that your tests cover all parts of your code and identify areas for improvement. + +### Debugger Statement + +The `debugger` statement allows you to pause the execution of your code at a specific point. When the code reaches the `debugger` statement, it will pause, and you can inspect the variables and step through the code using the controls in the debugger. This is useful for debugging complex issues and identifying errors in your code. + +```javascript title="Debugger Statement" +function add(a, b) { + debugger; + return a + b; +} + +add(1, 2); // The code will pause at the debugger statement +``` + +### Error Messages + +Error messages in the console provide valuable information about issues in your code. They help you identify syntax errors, runtime errors, and logic errors. By reading error messages, you can quickly pinpoint the source of the issue and fix it. + +### Code Review + +Code review is a collaborative process where you review your code with a colleague to get a fresh perspective. By sharing your code with others, you can identify issues, improve the quality of your code, and learn new techniques. Code review helps you catch bugs early, improve code readability, and foster a culture of collaboration. + +:::note +Debugging is an iterative process that requires patience and persistence. By mastering the debugging techniques and tools available to you, you can identify and fix errors in your code quickly and efficiently. +::: + +:::tip +When debugging, start with the simplest possible case and gradually add complexity. Break down the problem into smaller parts, test each part individually, and identify the source of the issue. By following a systematic approach, you can debug your code effectively and efficiently. +::: + +:::tip Major Browsers' Debugging Tools + +- **Chrome DevTools**: Built into Google Chrome, it provides a rich set of debugging tools for web developers. +- **Firefox Developer Tools**: Built into Mozilla Firefox, it provides a set of debugging tools for web developers. +- **Safari Web Inspector**: Built into Apple Safari, it provides a set of debugging tools for web developers. +- **Edge DevTools**: Built into Microsoft Edge, it provides a set of debugging tools for web developers. +- **Opera Developer Tools**: Built into Opera, it provides a set of debugging tools for web developers. +- **Internet Explorer Developer Tools**: Built into Internet Explorer, it provides a set of debugging tools for web developers. +- **Brave DevTools**: Built into Brave, it provides a set of debugging tools for web developers. +- **Vivaldi DevTools**: Built into Vivaldi, it provides a set of debugging tools for web developers. +- **Tor Browser DevTools**: Built into Tor Browser, it provides a set of debugging tools for web developers. +- **UC Browser DevTools**: Built into UC Browser, it provides a set of debugging tools for web developers. +- **Yandex Browser DevTools**: Built into Yandex Browser, it provides a set of debugging tools for web developers. +- **Samsung Internet DevTools**: Built into Samsung Internet, it provides a set of debugging tools for web developers. +- **Puffin Browser DevTools**: Built into Puffin Browser, it provides a set of debugging tools for web developers. + +::: + +## Conclusion + +In this tutorial, you learned how to debug JavaScript code in the browser using the Chrome DevTools. We covered the basics of debugging, including breakpoints, console, sources, call stack, watch, scope, network, performance, memory, profiling, and code coverage. By mastering these debugging techniques, you can identify and fix errors in your code quickly and efficiently. Happy debugging! diff --git a/languages-platforms/javascript/errors.md b/languages-platforms/javascript/errors.md new file mode 100644 index 0000000..f6a0366 --- /dev/null +++ b/languages-platforms/javascript/errors.md @@ -0,0 +1,178 @@ +--- +id: errors-in-javascript +title: Errors in JavaScript +sidebar_label: Errors +sidebar_position: 31 +tags: [JavaScript, Errors, Try Catch Finally, Error Object, Throw Error, Error Handling, DOMException, AggregateError, TypeError, RangeError, URIError, EvalError, InternalError, Error, AbortError, NotAllowedError, NotFoundError, SecurityError, try, catch, finally] +description: "In this tutorial, we will learn about errors in JavaScript. Errors are unexpected events that occur during the execution of a program. We will see the different types of errors in JavaScript and how to handle them using try...catch...finally blocks." +--- + +In JavaScript, an error is an unexpected event that occurs during the execution of a program. Errors can occur due to various reasons such as incorrect syntax, logical errors, or runtime errors. When an error occurs, JavaScript stops the execution of the program and generates an error message. + +JavaScript provides a built-in `Error` object that represents an error. The `Error` object contains information about the error such as the error message and the stack trace. The stack trace is a list of function calls that were in progress when the error occurred. + +There are several types of errors in JavaScript. Some common types of errors are: + +1. **SyntaxError**: This error occurs when there is a syntax error in the code. For example, missing parentheses, missing semicolons, or misspelled keywords. +2. **ReferenceError**: This error occurs when a variable or function is used without being declared. +3. **TypeError**: This error occurs when a value is not of the expected type. For example, trying to call a non-function value. +4. **RangeError**: This error occurs when a value is not within the expected range. For example, using an invalid index in an array. +5. **URIError**: This error occurs when a global URI handling function is used in a wrong way. +6. **EvalError**: This error occurs when an error occurs during the execution of `eval()` function. +7. **InternalError**: This error occurs when an internal error in the JavaScript engine occurs. +8. **Error**: This is the base class for all errors in JavaScript. +9. **AggregateError**: This error is a subclass of `Error` that represents an error when multiple errors need to be wrapped in a single error. +10. **DOMException**: This error is a subclass of `Error` that represents an error in the DOM. +11. **AbortError**: This error is a subclass of `DOMException` that represents an error when an operation is aborted. +12. **NotAllowedError**: This error is a subclass of `DOMException` that represents an error when an operation is not allowed. +13. **NotFoundError**: This error is a subclass of `DOMException` that represents an error when a requested resource is not found. +14. **SecurityError**: This error is a subclass of `DOMException` that represents a security error. +15. **TypeError**: This error is a subclass of `Error` that represents a type error. +16. **RangeError**: This error is a subclass of `Error` that represents a range error. + +## Handling Errors in JavaScript + +To handle errors in JavaScript, you can use the `try...catch...finally` statement. The `try` block contains the code that may throw an error. The `catch` block contains the code to handle the error. The `finally` block contains the code that will be executed regardless of whether an error occurs or not. + +Here is the syntax of the `try...catch...finally` statement: + +```javascript title="app.js" +try { + // Code that may throw an error +} catch (error) { + // Code to handle the error +} finally { + // Code that will be executed regardless of whether an error occurs or not +} +``` + +Let's see an example of handling errors in JavaScript using the `try...catch...finally` statement: + +```javascript title="app.js" +try { + let x = 10; + let y = 0; + let result = x / y; // Division by zero + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} finally { + console.log("Finally block executed"); +} +``` + +In this example, we are trying to divide a number by zero, which will throw a `TypeError` (division by zero). We are handling this error using the `try...catch...finally` statement. + +When you run the above code, you will get the following output: + +```bash title="Output" +An error occurred: Division by zero +Finally block executed +``` + +In the `catch` block, we are logging the error message using `error.message`. In the `finally` block, we are logging a message that will be executed regardless of whether an error occurs or not. + +That's all for handling errors in JavaScript. You can use the `try...catch...finally` statement to handle errors and prevent your program from crashing when an error occurs. + + +:::tip ๐Ÿง  Knowledge Check +1. Which of the following is not a type of error in JavaScript? + + A) SyntaxError
+ B) ReferenceError
+ C) TypeError
+ D) NullError + +
+ Answer +

+ + **Answer:** D) NullError + + `NullError` is not a type of error in JavaScript. The correct type of error is `TypeError`. + +

+
+ +2. Which block of code will be executed regardless of whether an error occurs or not? + + A) `try` block
+ B) `catch` block
+ C) `finally` block
+ D) None of the above + +
+ Answer +

+ + **Answer:** C) `finally` block + + The `finally` block will be executed regardless of whether an error occurs or not. + +

+
+ +::: + +:::info ๐Ÿ“š Learn More: + +**Throwing Errors in JavaScript:** + +You can throw an error in JavaScript using the `throw` statement. The `throw` statement allows you to create a custom error and throw it. Here is an example of throwing an error in JavaScript: + +```javascript title="app.js" +try { + let x = 10; + let y = 0; + if (y === 0) { + throw new Error("Division by zero"); + } + let result = x / y; + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} finally { + console.log("Finally block executed"); +} +``` + +In this example, we are throwing a custom error using the `throw` statement when the value of `y` is zero. The error message is "Division by zero". + +When you run the above code, you will get the following output: + +```bash title="Output" +An error occurred: Division by zero +Finally block executed +``` + +In the `catch` block, we are logging the error message using `error.message`. In the `finally` block, we are logging a message that will be executed regardless of whether an error occurs or not. + +**Error Object in JavaScript:** + +The `Error` object in JavaScript has two properties: `name` and `message`. The `name` property contains the name of the error (e.g., "SyntaxError", "ReferenceError", "TypeError"), and the `message` property contains the error message. + +Here is an example of creating a custom error using the `Error` object: + +```javascript title="app.js" +try { + throw new Error("Custom Error"); +} catch (error) { + console.log("An error occurred: " + error.message); +} +``` + +In this example, we are creating a custom error using the `Error` object with the message "Custom Error". + +When you run the above code, you will get the following output: + +```bash title="Output" +An error occurred: Custom Error +``` + +That's all for throwing errors in JavaScript. You can use the `throw` statement to throw custom errors and handle them using the `try...catch...finally` statement. + +::: + +## Summary + +In this tutorial, we learned about errors in JavaScript. Errors are unexpected events that occur during the execution of a program. We saw the different types of errors in JavaScript and how to handle them using the `try...catch...finally` statement. We also saw an example of handling errors in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/events-js.md b/languages-platforms/javascript/events-js.md new file mode 100644 index 0000000..ba28c98 --- /dev/null +++ b/languages-platforms/javascript/events-js.md @@ -0,0 +1,325 @@ +--- +id: events-in-javascript +title: Events in JavaScript +sidebar_label: Events +sidebar_position: 12 +tags: [JavaScript, Events, DOM, EventListener, EventObject, EventPropagation, PreventDefault, StopPropagation, EventTypes, ClickEvent, MouseoverEvent, MouseoutEvent, ChangeEvent, SubmitEvent, EventCapturePhase, EventBubblingPhase, EventTarget, EventListener, CallbackFunction, EventObject, EventProperties, UIEvents, MouseEvents, KeyboardEvents, FormEvents, FocusEvents, InputEvents, WheelEvents, TouchEvents, CustomEvents, AddEventListener, Options, Capture, Once, Passive, HandleEvent, EventPropagation, EventBubbling, EventCapture, EventPhase, EventTypes, EventListener, EventObject, EventProperties] +description: What is the event in JavaScript? How to handle events in JavaScript? Learn about different types of events, event listeners, event objects, event propagation, and how to prevent default behavior and stop event propagation. +--- + +An event is a signal that something has happened. For example, when a user clicks a button, the click event is triggered. Events are a part of the Document Object Model (DOM) and are used to interact with the user. + +```mermaid +graph LR +A[User] -->|Clicks Button| B[Event] +B -->|Triggers| C[Event Listener] +C -->|Executes| D[Function] +``` + +In the above diagram, when a user clicks a button, the click event is triggered. The event listener listens for the click event and executes the function when the event occurs. + +## Event Types + +There are many types of events in JavaScript. Some of the most common events are: + +### 1. `click` Event + +```html title="index.html" + + + + Click Event + + + + + + +``` + + + + + +### 2. `mouseover` Event + +```html title="index.html" + + + + Mouseover Event + + + + + + +``` + + + + + +### 3. `mouseout` Event + +```html title="index.html" + + + + Mouseout Event + + + + + + +``` + + + + + +### 3. `change` Event + +```html title="index.html" + + + + Change Event + + + + + + +``` + + + alert("Input Changed")} /> + + +### 4. `submit` Event + +```html title="index.html" + + + + Submit Event + + +
+ + +
+ + + +``` + + +
{e.preventDefault(); alert("Form Submitted")}}> + + {' '} + +
+
+ +## Event Listener + +An event listener is a function that listens for a specific event to occur. It is used to handle the event when it occurs. The `addEventListener` method is used to add an event listener to an element. + +```js title="index.js" +document.getElementById("button").addEventListener("click", function () { + alert("Button Clicked"); +}); +``` + +In the above example, the `click` event listener is added to the button element. When the button is clicked, the function is executed. + +## Event Object + +The event object is passed to the event listener function as an argument. It contains information about the event that occurred. For example, the `target` property of the event object contains a reference to the element that triggered the event. + +```js title="index.js" +document.getElementById("button").addEventListener("click", function (event) { + alert("Button Clicked"); + console.log(event.target); +}); +``` + +In the above example, the `target` property of the event object is logged to the console. It contains a reference to the button element that triggered the event. + +## Event Propagation + +Event propagation is the process of event bubbling and event capturing. When an event occurs on an element, it first runs the event listeners on the element itself, then on its parent, and so on, until it reaches the top of the document. This is called event bubbling. Event capturing is the opposite, where the event listeners on the parent element are run first, then on the element itself. + +```html title="index.html" + + + + Event Propagation + + +
+
Click Me
+
+ + + +``` + + +
alert("Outer Div Clicked")}> +
alert("Inner Div Clicked")}>Click Me
+
+
+ +In the above example, when the inner div is clicked, the event bubbles up to the outer div, and the event listener on the outer div is also triggered. + +## Prevent Default + +The `preventDefault` method is used to prevent the default behavior of an event. For example, it can be used to prevent a form from being submitted or a link from being followed. + +```html title="index.html" + + + + Prevent Default + + + Click Me + + + +``` + + + {e.preventDefault(); alert("Link Clicked")}}>Click Me + + +In the above example, the `preventDefault` method is used to prevent the link from being followed when it is clicked. + +## Stop Propagation + +The `stopPropagation` method is used to stop the event from propagating to the parent elements. It prevents the event from bubbling up the DOM tree. + +```html title="index.html" + + + + Stop Propagation + + +
+
Click Me
+
+ + + +``` + + +
alert("Outer Div Clicked")}> +
{e.stopPropagation(); alert("Inner Div Clicked")}}>Click Me
+
+
+ +In the above example, when the inner div is clicked, the event does not bubble up to the outer div because the `stopPropagation` method is used. + +:::info +The `stopPropagation` method only stops the event from propagating to the parent elements. It does not stop the default behavior of the event. +::: + +```mermaid +flowchart TD + subgraph "DOM" + A[Event Phase] --> B[Event Capture Phase] + B --> C[Target Element] + C --> D[Event Bubbling Phase] + D --> E[Event Propagation] + end + subgraph "Event" + E --> F[Event Types] + F --> G[UI Events] + F --> H[Mouse Events] + F --> I[Keyboard Events] + F --> J[Form Events] + F --> K[Focus Events] + F --> L[Input Events] + F --> M[Wheel Events] + F --> N[Touch Events] + F --> O[Custom Events] + end + subgraph "Event Target" + C --> P[Target Element] + P --> Q[Parent Element] + Q --> R[Ancestor Elements] + end + subgraph "Event Listener" + S[AddEventListener] --> T[Options] + T --> U[Capture] + T --> V[Once] + T --> W[Passive] + end + subgraph "Callback Function" + X[Handle Event] --> Y[Event Object] + Y --> Z[Event Properties] + end +``` + +In the above diagram, the event capture phase occurs first, followed by the target element, and then the event bubbling phase. The event object contains information about the event, and the event listener is used to handle the event when it occurs. + +## Summary + +In this article, we learned about events in JavaScript. We learned about different types of events, event listeners, event objects, event propagation, and how to prevent default behavior and stop event propagation. Events are an important part of web development and are used to create interactive user interfaces. diff --git a/languages-platforms/javascript/for-in-loop.md b/languages-platforms/javascript/for-in-loop.md new file mode 100644 index 0000000..0672c8f --- /dev/null +++ b/languages-platforms/javascript/for-in-loop.md @@ -0,0 +1,155 @@ +--- +id: for-in-loop-in-javascript +title: For In Loop in JavaScript +sidebar_label: For...In +sidebar_position: 22 +tags: + [ + JavaScript, + For In Loop, + Loop, + Iteration, + Control, + Flow, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the for...in loop in JavaScript. We will learn how to use the for...in loop to iterate over the properties of an object in JavaScript." +--- + +In JavaScript, the `for...in` loop is used to iterate over the properties of an object. It is often used when you want to perform an action on each property of an object. + +## Syntax + +The syntax of the `for...in` loop is as follows: + +```js title="app.js" +for (variable in object) { + // code to be executed +} +``` + +- The `for...in` loop starts with the `for` keyword followed by parentheses. +- Inside the parentheses, you need to specify a `variable` to hold the property name and the `object` over which you want to iterate. +- The `variable` will be assigned the property name of the object on each iteration. +- The code inside the loop will be executed for each property of the object. +- The loop will iterate over all enumerable properties of the object, including inherited properties from the object's prototype chain. +- The order of iteration is not guaranteed and may vary between different JavaScript engines. +- It is recommended to use the `hasOwnProperty` method to check if the property is a direct property of the object and not inherited from its prototype chain. +- The `for...in` loop should not be used to iterate over arrays, as it may produce unexpected results due to the iteration of array indices and inherited properties. +- The `for...in` loop should be used only for objects. + +## Example + +The following example demonstrates how to use the `for...in` loop to iterate over the properties of an object: + +```js title="app.js" +const person = { + name: "John", + age: 23, + // Method + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}; + +for (let property in person) { + console.log(property + ": " + person[property]); +} +``` + +In this example, the `for...in` loop iterates over the properties of the `person` object. On each iteration, the `property` variable is assigned the name of the property, and the code inside the loop logs the property name and its value to the console. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); +} +``` + +In each iteration, the property name and its value are printed to the console. + +## Using `hasOwnProperty` Method + +To check if the property is a direct property of the object and not inherited from its prototype chain, you can use the `hasOwnProperty` method. Here's an example: + +```js title="app.js" +const person = { + name: "John", + age: 23, + // Method + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}; + +for (let property in person) { + if (person.hasOwnProperty(property)) { + console.log(property + ": " + person[property]); + } +} +``` + +In this example, the `hasOwnProperty` method is used to check if the property is a direct property of the `person` object. If it is, the property name and its value are printed to the console. + +:::tip tips & tricks +The `hasOwnProperty` method returns `true` if the property is a direct property of the object, otherwise it returns `false`. + +The `for...in` loop should be used with caution, as it iterates over all enumerable properties of the object, including inherited properties from the object's prototype chain. It is recommended to use the `hasOwnProperty` method to check if the property is a direct property of the object. + +The `for...in` loop should not be used to iterate over arrays, as it may produce unexpected results due to the iteration of array indices and inherited properties. + +The `for...in` loop should be used only for objects. + +::: + +:::info ๐Ÿ“š Learn Extra + +## Array.forEach Method + +If you want to iterate over the elements of an array, you can use the `forEach` method. The `forEach` method is a more appropriate way to iterate over the elements of an array, as it provides a concise and readable syntax for performing actions on each element of the array. + +Here's an example that demonstrates the use of the `forEach` method to iterate over the elements of an array: + +```js title="app.js" +const numbers = [1, 2, 3, 4, 5]; + +numbers.forEach(function (number) { + console.log(number); +}); +``` + +In this example, the `forEach` method iterates over the elements of the `numbers` array and executes the provided function for each element. + +The `forEach` method is a convenient and concise way to iterate over the elements of an array in JavaScript. + +## Array.forEach Method vs. for...of Loop vs. for...in Loop Comparison + +| No. | forEach Method | for...of Loop | for...in Loop | +| :-: | :-------------------------------------------------------- | :-------------------------------------------------------- | :------------------------------------------------ | +| 1. | Iterates over the elements of an array. | Iterates over the elements of an iterable object. | Iterates over the properties of an object. | +| 2. | Provides a concise and readable syntax. | Provides a concise and readable syntax. | Provides a concise and readable syntax. | +| 3. | Should be used for arrays. | Should be used for iterable objects. | Should be used for objects. | +| 4. | Does not iterate over inherited properties. | Does not iterate over inherited properties. | Iterates over inherited properties. | +| 5. | Does not iterate over array indices. | Does not iterate over array indices. | Iterates over array indices. | +| 6. | Does not require a loop variable. | Requires a loop variable. | Requires a loop variable. | +| 7. | Does not require an explicit check for direct properties. | Does not require an explicit check for direct properties. | Requires an explicit check for direct properties. | + +::: + +## Summary + +In this tutorial, we learned about the `for...in` loop in JavaScript. We learned how to use the `for...in` loop to iterate over the properties of an object. We also learned about using the `hasOwnProperty` method to check if the property is a direct property of the object and not inherited from its prototype chain. diff --git a/languages-platforms/javascript/for-loop.md b/languages-platforms/javascript/for-loop.md new file mode 100644 index 0000000..009e783 --- /dev/null +++ b/languages-platforms/javascript/for-loop.md @@ -0,0 +1,145 @@ +--- +id: for-loop-in-javascript +title: For Loop in JavaScript +sidebar_label: For Loop +sidebar_position: 21 +tags: + [ + JavaScript, + For Loop, + Loop, + Iteration, + Control, + Flow, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the for loop in JavaScript. We will learn how to use the for loop to execute a block of code multiple times in JavaScript." +--- + +In JavaScript, the `for` loop is used to execute a block of code multiple times. It is often used when you know the number of iterations you want to perform. + +## Syntax + +The syntax of the `for` loop is as follows: + +```js title="app.js" +for (initialization; condition; increment / decrement) { + // code to be executed +} +``` + +- The `for` loop starts with the `for` keyword followed by parentheses. +- Inside the parentheses, you need to specify three expressions separated by semicolons: + - The `initialization` expression is executed only once before the loop starts. It is used to initialize the loop variable. + - The `condition` expression is evaluated before each iteration. If the condition is `true`, the code inside the loop is executed. If the condition is `false`, the loop terminates. + - The `increment/decrement` expression is executed at the end of each iteration. It is used to update the loop variable. + +## Flow Chart of the `for` Loop + +```mermaid +graph TD; + Start([Start]) --> Initialization; + Initialization -->|Condition| Condition{Condition}; + Condition -->|True| Action; + Action --> Increment[Increment/Decrement]; + Increment --> Condition{Condition}; + Condition -->|False| Stop; + Stop --> End([End]); +``` + +## Example + +The following example demonstrates how to use the `for` loop to print the numbers from 1 to 5: + +```js title="app.js" +for (let i = 1; i <= 5; i++) { + console.log(i); +} +``` + +In this example, the `for` loop initializes the loop variable `i` to `1`. It then checks if `i` is less than or equal to `5`. If the condition is `true`, it executes the code inside the loop and increments `i` by `1`. This process continues until `i` is no longer less than or equal to `5`. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +3 +4 +5 +``` + +In each iteration, the value of `i` is printed to the console. + +## Infinite `for` Loop + +If you omit the `condition` expression, the `for` loop will run indefinitely. This is known as an infinite loop. For example: + +```js title="app.js" +for (let i = 1; ; i++) { + console.log(i); +} +``` + +In this example, the `condition` expression is omitted, so the loop will run indefinitely. You can use the `break` statement to exit the loop when a certain condition is met. + +## Nested `for` Loop + +You can use a `for` loop inside another `for` loop. This is known as a nested `for` loop. For example: + +```js title="app.js" +for (let i = 1; i <= 3; i++) { + for (let j = 1; j <= 3; j++) { + console.log(`i = ${i}, j = ${j}`); + } +} +``` + +In this example, the outer `for` loop runs three times, and the inner `for` loop runs three times for each iteration of the outer loop. The output of the above example will be: + +```plaintext title="Output" +i = 1, j = 1 +i = 1, j = 2 +i = 1, j = 3 +i = 2, j = 1 +i = 2, j = 2 +i = 2, j = 3 +i = 3, j = 1 +i = 3, j = 2 +i = 3, j = 3 +``` + +In each iteration of the outer loop, the inner loop runs three times, printing the value of `i` and `j` to the console. + +:::info ๐Ÿ“ Note + +**1.** You can use the `break` statement to exit a `for` loop prematurely. You can also use the `continue` statement to skip the current iteration and continue with the next iteration. + +**2. Live Example** + +```js live +function printNumbers() { + return ( +
+ {(() => { + let numbers = []; + for (let i = 1; i <= 5; i++) { + numbers.push(

{i}

); + } + return numbers; + })()} +
+ ); +} +``` + +::: + +## Conclusion + +In this tutorial, you learned about the `for` loop in JavaScript and how to use it to execute a block of code multiple times. You also learned about infinite `for` loops and nested `for` loops. diff --git a/languages-platforms/javascript/for-of-loop.md b/languages-platforms/javascript/for-of-loop.md new file mode 100644 index 0000000..73af1b8 --- /dev/null +++ b/languages-platforms/javascript/for-of-loop.md @@ -0,0 +1,139 @@ +--- +id: for-of-loop-in-javascript +title: For Of Loop in JavaScript +sidebar_label: For...Of +sidebar_position: 23 +tags: + [ + JavaScript, + For Of Loop, + Loop, + Iteration, + Control, + Flow, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about the for...of loop in JavaScript. We will learn how to use the for...of loop to iterate over the elements of an iterable object in JavaScript." +--- + +In JavaScript, the `for...of` loop is used to iterate over the elements of an iterable object. It is often used when you want to perform an action on each element of an array, set, map, string, or any other iterable object. + +## Syntax + +The syntax of the `for...of` loop is as follows: + +```js title="app.js" +for (variable of iterable) { + // code to be executed +} +``` + +- The `for...of` loop starts with the `for` keyword followed by parentheses. +- Inside the parentheses, you need to specify a `variable` to hold the element value and the `iterable` over which you want to iterate. +- The `variable` will be assigned the value of each element of the iterable on each iteration. +- The code inside the loop will be executed for each element of the iterable. +- The loop will iterate over the elements of the iterable object in the order of their insertion. +- The `for...of` loop can be used with arrays, sets, maps, strings, and any other iterable object. +- The `for...of` loop cannot be used to iterate over plain objects (i.e., objects created using `{}`) because they are not iterable. To iterate over the properties of an object, you should use the `for...in` loop or the `Object.keys`, `Object.values`, or `Object.entries` methods. +- The `for...of` loop can also be used with generator functions to iterate over the values generated by the generator. +- The `for...of` loop cannot be used to iterate over asynchronous iterators, such as the iterators returned by the `Symbol.asyncIterator` method. +- The `for...of` loop can be used with the `await` keyword to iterate over the values of asynchronous iterators in an asynchronous function. +- The `for...of` loop can be used with the `break` and `continue` statements to control the flow of the loop. + +## Example + +The following example demonstrates how to use the `for...of` loop to iterate over the elements of an array: + +```js title="app.js" +const numbers = [1, 2, 3, 4, 5]; + +for (const number of numbers) { + console.log(number); +} +``` + +In this example, the `for...of` loop iterates over the elements of the `numbers` array and assigns each element to the `number` variable on each iteration. It then executes the code inside the loop to log each element to the console. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +3 +4 +5 +``` + +The `for...of` loop is a convenient and concise way to iterate over the elements of an iterable object in JavaScript. It provides a simple and readable syntax for performing actions on each element of the iterable. + +## Flow Chart of the `for...of` Loop + +```mermaid +graph TD; + Start([Start]) --> Initialization; + Initialization -->|Condition| Condition{Condition}; + Condition -->|True| Action; + Action --> Increment[Next Element]; + Increment --> Condition{Condition}; + Condition -->|False| Stop; + Stop --> End([End]); +``` + +The flow chart above illustrates the flow of the `for...of` loop. It starts with the `Initialization` step, where the loop variable is initialized to the first element of the iterable. It then checks the `Condition` before each iteration. If the condition is `true`, it executes the `Action` and moves to the next element. This process continues until the condition is `false`, at which point the loop stops. + +## Using `break` and `continue` Statements + +You can use the `break` and `continue` statements to control the flow of the `for...of` loop. The `break` statement can be used to terminate the loop prematurely, while the `continue` statement can be used to skip the current iteration and move to the next element. + +Here's an example that demonstrates the use of the `break` and `continue` statements with the `for...of` loop: + +```js title="app.js" +const numbers = [1, 2, 3, 4, 5]; + +for (const number of numbers) { + if (number === 3) { + continue; // Skip the number 3 + } + + if (number === 5) { + break; // Terminate the loop when the number 5 is encountered + } + + console.log(number); +} +``` + +In this example, the `continue` statement is used to skip the number `3`, and the `break` statement is used to terminate the loop when the number `5` is encountered. The code inside the loop logs the numbers to the console, skipping the number `3` and terminating the loop when the number `5` is encountered. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +4 +``` + +In each iteration, the code inside the loop checks if the current number is `3` or `5`. If the number is `3`, it skips the current iteration using the `continue` statement. If the number is `5`, it terminates the loop using the `break` statement. Otherwise, it logs the number to the console. + +The `for...of` loop is a powerful and flexible construct that provides a convenient way to iterate over the elements of an iterable object in JavaScript. It can be used with arrays, sets, maps, strings, and any other iterable object to perform actions on each element in a concise and readable manner. + +:::tip ๐Ÿ“ Note + +The `for...of` loop cannot be used to iterate over plain objects (i.e., objects created using `{}`) because they are not iterable. To iterate over the properties of an object, you should use the `for...in` loop or the `Object.keys`, `Object.values`, or `Object.entries` methods. + +The `for...of` loop can also be used with generator functions to iterate over the values generated by the generator. + +The `for...of` loop cannot be used to iterate over asynchronous iterators, such as the iterators returned by the `Symbol.asyncIterator` method. However, it can be used with the `await` keyword to iterate over the values of asynchronous iterators in an asynchronous function. + +The `for...of` loop can be used with the `break` and `continue` statements to control the flow of the loop. + +::: + +## Summary + +In this tutorial, we learned about the `for...of` loop in JavaScript. We learned how to use the `for...of` loop to iterate over the elements of an iterable object. We also learned about using the `break` and `continue` statements to control the flow of the loop. The `for...of` loop is a powerful and flexible construct that provides a convenient and concise way to iterate over the elements of an iterable object in JavaScript. diff --git a/languages-platforms/javascript/if-else.md b/languages-platforms/javascript/if-else.md new file mode 100644 index 0000000..266b6e6 --- /dev/null +++ b/languages-platforms/javascript/if-else.md @@ -0,0 +1,94 @@ +--- +id: if-else-in-javascript +title: If...Else in JavaScript +sidebar_label: If...Else +sidebar_position: 19 +tags: [JavaScript, Conditional, Statement, If, Else, Ternary, Operator, Nested, Switch, Nullish, Coalescing, Operator, Decision, Making, Control, Flow, Conditional, Statements] +description: "In this tutorial, we will learn about the if...else statement in JavaScript. We will learn how to use the if...else statement to make decisions in JavaScript." +--- + +In JavaScript, the `if...else` statement is used to execute a block of code if a specified condition is true. If the condition is false, another block of code can be executed. + +## Syntax + +The syntax of the `if...else` statement is as follows: + +```js title="app.js" +if (condition) { + // code to be executed if the condition is true +} else { + // code to be executed if the condition is false +} +``` + +## Example + +The following example demonstrates how to use the `if...else` statement to check if a number is even or odd: + +```js title="app.js" +let num = 10; + +if (num % 2 === 0) { + console.log(`${num} is even`); +} else { + console.log(`${num} is odd`); +} +``` + +In the above example, the `if...else` statement checks if the number `num` is even or odd and logs the result to the console. + +## Nested if...else + +You can also use the `if...else` statement inside another `if...else` statement. This is known as a nested `if...else` statement. + +The following example demonstrates how to use a nested `if...else` statement to check if a number is positive, negative, or zero: + +```js title="app.js" +let num = 10; + +if (num > 0) { + console.log(`${num} is positive`); +} else if (num < 0) { + console.log(`${num} is negative`); +} else { + console.log(`${num} is zero`); +} +``` + +In the above example, the nested `if...else` statement checks if the number `num` is positive, negative, or zero and logs the result to the console. + +## Ternary Operator + +The `if...else` statement can also be written using the ternary operator (`? :`). + +The following example demonstrates how to use the ternary operator to check if a number is even or odd: + +```js title="app.js" +let num = 10; + +const result = num % 2 === 0 ? `${num} is even` : `${num} is odd`; + +console.log(result); +``` + +In the above example, the ternary operator checks if the number `num` is even or odd and assigns the result to the `result` variable. + +:::info ๐Ÿ“ Note +

Conditional Statements

+ +The `if...else` statement is a conditional statement that executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed. + +In JavaScript we have the following conditional statements: + +- **`if` statement:** executes a block of code if a specified condition is true. +- **`if...else` statement:** executes a block of code if a specified condition is true and another block of code if the condition is false. +- **`if...else if...else` statement:** executes a block of code if a specified condition is true, another block of code if another condition is true, and another block of code if the conditions are false. +- **`switch` statement:** selects one of many code blocks to be executed. +- **`ternary operator`:** assigns a value to a variable based on a specified condition. +- **`nullish coalescing operator`:** returns the right-hand operand when the left-hand operand is `null` or `undefined`. + +::: + +## Conclusion + +In this tutorial, we learned about the `if...else` statement in JavaScript. We learned how to use the `if...else` statement to make decisions in JavaScript. We also saw examples of how to use the `if...else` statement to check if a number is even or odd and to check if a number is positive, negative, or zero. \ No newline at end of file diff --git a/languages-platforms/javascript/img/breakpoints.gif b/languages-platforms/javascript/img/breakpoints.gif new file mode 100644 index 0000000..51bf4aa Binary files /dev/null and b/languages-platforms/javascript/img/breakpoints.gif differ diff --git a/languages-platforms/javascript/img/call-stack.gif b/languages-platforms/javascript/img/call-stack.gif new file mode 100644 index 0000000..6913e4a Binary files /dev/null and b/languages-platforms/javascript/img/call-stack.gif differ diff --git a/languages-platforms/javascript/img/source.gif b/languages-platforms/javascript/img/source.gif new file mode 100644 index 0000000..e437da1 Binary files /dev/null and b/languages-platforms/javascript/img/source.gif differ diff --git a/languages-platforms/javascript/intro-js.md b/languages-platforms/javascript/intro-js.md new file mode 100644 index 0000000..a57e81d --- /dev/null +++ b/languages-platforms/javascript/intro-js.md @@ -0,0 +1,234 @@ +--- +id: intro-js +title: Introduction to JavaScript +sidebar_label: Introduction to JavaScript +sidebar_position: 1 +tags: [JavaScript, Introduction of js, Introduction of JavaScript] +description: What is JavaScript? Why JavaScript? How to use JavaScript? Learn about JavaScript in this tutorial. +--- + +JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. + +> JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers. + +## What is JavaScript? + +JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. JavaScript is a scripting language. JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. It is a dynamic, weakly typed, prototype-based language with first-class functions. JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. + +:::note + +## Key Points + +- JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. +- It is a dynamic, weakly typed, prototype-based language with first-class functions. +- JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. +- JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. +- JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers. +- JavaScript is a programming language that enables you to create dynamically updating content, control multimedia, animate images, and much more. +- JavaScript is a scripting language. +- JavaScript is a high-level, interpreted programming language that is used to make web pages interactive. +- It is a dynamic, weakly typed, prototype-based language with first-class functions. +- JavaScript is a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. +- JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. + +::: + +## Why JavaScript? + +JavaScript is scripting language that enables you to create dynamically updating content, control multimedia, animate imsages, and much more. And it is the most popular programming language in the world. JavaScript is the programming language of the Web. The overwhelming majority of websites use JavaScript, and all modern web browsersโ€”on desktops, game consoles, tablets, and smartphones include JavaScript interpreters, making it an essential part of the web platform. + +## How to use JavaScript? + +JavaScript can be used in a lot of different ways. Here are a few examples: + +### 1. JavaScript Can Change HTML Content + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

Welcome CodeHarborHub Learners!

+
+ +### 2. JavaScript Can Change HTML Styles + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+
+ +### 3. JavaScript Can Hide HTML Elements + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+ +
+ +### 4. JavaScript Can Show HTML Elements + +```html title="index.html" + + + +

My First JavaScript

+ + + + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+ +
+ +### 5. JavaScript Can Change HTML Attributes + +```html title="index.html" + + + +

My First JavaScript

+ +

This is a paragraph.

+ + + + +``` + + +

My First JavaScript

+

This is a paragraph.

+ +
+ +### 6. JavaScript Can Change HTML Image + +```html title="index.html" + + + +

My First JavaScript

+ + + + + + +``` + + +

My First JavaScript

+ + +
+ +### 7. JavaScript Can Validate Data + +```html title="index.html" + + + +

My First JavaScript

+ +
+ Email: + +
+ + + + +``` + +## Conclusion + +In this article, we have learned about JavaScript, its introduction, and its usage. We have also seen how JavaScript can be used to change HTML content, styles, and attributes. We have also seen how JavaScript can be used to validate data. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/_category_.json b/languages-platforms/javascript/js-versions/_category_.json new file mode 100644 index 0000000..65cc4e4 --- /dev/null +++ b/languages-platforms/javascript/js-versions/_category_.json @@ -0,0 +1,8 @@ +{ + "label": "Versions of JavaScript", + "position": 44, + "link": { + "type": "generated-index", + "description": "JavaScript was invented by Brendan Eich in 1995, and became an ECMA standard in 1997. Since then, there have been several versions of JavaScript, each adding new features and improving the language. This page provides an overview of the different versions of JavaScript, and the features they introduced." + } + } \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2016.md b/languages-platforms/javascript/js-versions/js-2016.md new file mode 100644 index 0000000..62a8507 --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2016.md @@ -0,0 +1,90 @@ +--- +id: es2016-version-of-javascript +title: JavaScript ES2016 Version (2016) +sidebar_label: ES2016 Version (2016) +sidebar_position: 3 +tags: [JavaScript, ES2016, CMAScript 2016, JavaScript ES2016, JavaScript ES2016, JavaScript ES2016 Version, JavaScript ES2016 Version] +description: "In this tutorial, we will learn about the ES2016 version of JavaScript, also known as ECMAScript 2016. We will discuss the new features introduced in ES2016 and how to use them in your JavaScript code." +--- + +JavaScript ES2016 (ECMAScript 2016) is the seventh major release of the JavaScript language specification. It was finalized in June 2016. ES2016 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2016 and how to use them in your JavaScript code. + +## Features of ES2016 + +ES2016 introduced several new features and enhancements to JavaScript. Some of the key features of ES2016 are: + +1. **Exponentiation Operator (`**`)**: ES2016 introduced the exponentiation operator (`**`), which allows you to raise one number to the power of another number. For example, `2 ** 3` is equivalent to `2 * 2 * 2`. + + For example: + + ```javascript title="Exponentiation Operator Example" + let result = 2 ** 3; // 2 raised to the power of 3 + console.log(result); // Output: 8 + ``` + +2. **Array.prototype.includes()**: ES2016 introduced the `Array.prototype.includes()` method, which allows you to check if an array includes a specific element. It returns `true` if the array contains the element, and `false` otherwise. + + For example: + + ```javascript title="Array.prototype.includes() Example" + let numbers = [1, 2, 3, 4, 5]; + console.log(numbers.includes(3)); // Output: true + console.log(numbers.includes(6)); // Output: false + ``` + +3. **Additional Features**: ES2016 also introduced other minor features and enhancements to JavaScript, such as the `TypedArray.prototype.includes()` method for typed arrays and the `Object.values()` and `Object.entries()` methods for objects. + + For example: + + ```javascript title="Object.values() and Object.entries() Example" + let person = { name: "Alice", age: 30 }; + console.log(Object.values(person)); // Output: ["Alice", 30] + console.log(Object.entries(person)); // Output: [["name", "Alice"], ["age", 30]] + ``` + +## Browser Support for ES2016 + +Most modern web browsers support ES2016 features, but some older browsers may not fully support all ES2016 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2016 code into ES5 code, which is compatible with older browsers. + +ES2016 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2016 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 52+ | | 49+ | | 10.1+ | | 14+ | | 39+ | | No | | +| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โŒ| | + + +:::info ๐Ÿ“ Note + +- **Chrome**: 52+ (Latest โœ…) + + Chrome has full support for ES2016 features. You can use ES2016 features in Chrome without any issues. Chrome 52 and later versions fully support ES2016 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 49+ (Latest โœ…) + + Firefox has full support for ES2016 features. You can use ES2016 features in Firefox without any issues. Firefox 49 and later versions fully support ES2016 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 10.1+ (Latest โœ…) + + Safari has full support for ES2016 features. You can use ES2016 features in Safari without any issues. Safari 10.1 and later versions fully support ES2016 features. Safari is a popular web browser, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 14+ (Latest โœ…) + + Edge has full support for ES2016 features. You can use ES2016 features in Edge without any issues. Edge 14 and later versions fully support ES2016 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 39+ (Latest โœ…) + + Opera has full support for ES2016 features. You can use ES2016 features in Opera without any issues. Opera 39 and later versions fully support ES2016 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No (Latest โŒ) + + Internet Explorer does not support ES2016 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2016 code into ES5 code, which is compatible with Internet Explorer. + +::: + + +## Conclusion + +ES2016 introduced several new features and enhancements to JavaScript, such as the exponentiation operator, `Array.prototype.includes()` method, and `Object.values()` and `Object.entries()` methods. These features make it easier to work with numbers, arrays, and objects in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2017.md b/languages-platforms/javascript/js-versions/js-2017.md new file mode 100644 index 0000000..72fa4ba --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2017.md @@ -0,0 +1,123 @@ +--- +id: es2017-version-of-javascript +title: JavaScript ES2017 Version (2017) +sidebar_label: ES2017 Version (2017) +sidebar_position: 4 +tags: [JavaScript, ES2017, ECMAScript 2017, JavaScript ES2017, JavaScript ES2017, JavaScript ES2017 Version, JavaScript ES2017 Version] +description: "In this tutorial, we will learn about the ES2017 version of JavaScript, also known as ECMAScript 2017. We will discuss the new features introduced in ES2017 and how to use them in your JavaScript code." +--- + +JavaScript ES2017 (ECMAScript 2017) is the eighth major release of the JavaScript language specification. It was finalized in June 2017. ES2017 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2017 and how to use them in your JavaScript code. + +## Features of ES2017 + +ES2017 introduced several new features and enhancements to JavaScript. Some of the key features of ES2017 are: + +1. **Async/Await Functions**: ES2017 introduced the `async` and `await` keywords, which allow you to write asynchronous code that looks synchronous. The `async` keyword is used to define an asynchronous function, and the `await` keyword is used to pause the execution of an asynchronous function until a `Promise` is settled. + + For example: + + ```javascript title="Async/Await Example" + function delay(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); + } + + async function asyncFunction() { + console.log("Start"); + await delay(2000); + console.log("End"); + } + + asyncFunction(); + ``` + +2. **Object.values() and Object.entries()**: ES2017 introduced the `Object.values()` and `Object.entries()` methods, which allow you to get the values and entries of an object, respectively. The `Object.values()` method returns an array of the object's values, and the `Object.entries()` method returns an array of the object's key-value pairs. + + For example: + + ```javascript title="Object.values() and Object.entries() Example" + let person = { name: "Alice", age: 30 }; + console.log(Object.values(person)); // Output: ["Alice", 30] + console.log(Object.entries(person)); // Output: [["name", "Alice"], ["age", 30]] + ``` + +3. **String Padding**: ES2017 introduced the `String.prototype.padStart()` and `String.prototype.padEnd()` methods, which allow you to pad a string with spaces or other characters to a specified length. The `padStart()` method pads the string at the beginning, and the `padEnd()` method pads the string at the end. + + For example: + + ```javascript title="String Padding Example" + let str = "Hello"; + console.log(str.padStart(10, ".")); // Output: ".....Hello" + console.log(str.padEnd(10, ".")); // Output: "Hello....." + ``` + +4. **Shared Memory and Atomics**: ES2017 introduced the `SharedArrayBuffer` and `Atomics` objects, which allow you to work with shared memory and atomic operations in JavaScript. The `SharedArrayBuffer` object represents a shared memory region, and the `Atomics` object provides atomic operations for shared memory. + + For example: + + ```javascript title="Shared Memory and Atomics Example" + let buffer = new SharedArrayBuffer(16); + let view = new Int32Array(buffer); + view[0] = 42; + + Atomics.add(view, 0, 13); + console.log(view[0]); // Output: 55 + ``` + +## Browser Support for ES2017 + +Most modern web browsers support ES2017 features, but some older browsers may not fully support all ES2017 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2017 code into ES5 code, which is compatible with older browsers. + +ES2017 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2017 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 58+ | | 52+ | | 10.1+ | | 16+ | | 45+ | | No | | +| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โŒ| | + +:::info ๐Ÿ“ Note + +- **Chrome**: 58+ (Latest โœ…) + + Chrome has full support for ES2017 features. You can use ES2017 features in Chrome without any issues. Chrome 58 and later versions fully support ES2017 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 52+ (Latest โœ…) + + Firefox has full support for ES2017 features. You can use ES2017 features in Firefox without any issues. Firefox 52 and later versions fully support ES2017 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 10.1+ (Latest โœ…) + + Safari has full support for ES2017 features. You can use ES2017 features in Safari without any issues. Safari 10.1 and later versions fully support ES2017 features. Safari is a popular web browser, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 16+ (Latest โœ…) + + Edge has full support for ES2017 features. You can use ES2017 features in Edge without any issues. Edge 16 and later versions fully support ES2017 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 45+ (Latest โœ…) + + Opera has full support for ES2017 features. You can use ES2017 features in Opera without any issues. Opera 45 and later versions fully support ES2017 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No (Latest โŒ) + + Internet Explorer does not support ES2017 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2017 code into ES5 code, which is compatible with Internet Explorer. + +::: + +:::tip Important + +

Why Internet Explorer does not support ES2017 features?

+ +Internet Explorer does not support ES2017 features because it is an outdated web browser that has been replaced by Microsoft Edge. Microsoft Edge is the modern web browser from Microsoft that supports the latest web standards and features, including ES2017. It is recommended to use Microsoft Edge or other modern web browsers to ensure compatibility with the latest JavaScript features. If you need to support Internet Explorer for legacy reasons, you can use a transpiler like Babel to convert your ES2017 code into ES5 code, which is compatible with Internet Explorer. + +::: + + +ES2017 introduced several new features and enhancements to JavaScript, making it easier to write asynchronous code, work with objects, manipulate strings, and work with shared memory. You can start using ES2017 features in your JavaScript code to take advantage of these new capabilities. + +## Conclusion + +ES2017 introduced several new features and enhancements to JavaScript, such as async/await functions, Object.values() and Object.entries() methods, string padding methods, and shared memory and atomics. These features make it easier to work with asynchronous code, objects, strings, and shared memory in JavaScript. + +By using ES2017 features, you can write more expressive and concise JavaScript code that takes advantage of the latest language features and capabilities. You can start using ES2017 features in your JavaScript code to improve readability, maintainability, and performance. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2018.md b/languages-platforms/javascript/js-versions/js-2018.md new file mode 100644 index 0000000..426c95a --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2018.md @@ -0,0 +1,141 @@ +--- +id: es2018-version-of-javascript +title: JavaScript ES2018 Version (2018) +sidebar_label: ES2018 Version (2018) +sidebar_position: 5 +tags: [JavaScript, ES2018, ECMAScript 2018, JavaScript ES2018, JavaScript ES2018, JavaScript ES2018 Version, JavaScript ES2018 Version] +description: "In this tutorial, we will learn about the ES2018 version of JavaScript, also known as ECMAScript 2018. We will discuss the new features introduced in ES2018 and how to use them in your JavaScript code." +--- + +JavaScript ES2018 (ECMAScript 2018) is the ninth major release of the JavaScript language specification. It was finalized in June 2018. ES2018 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2018 and how to use them in your JavaScript code. + +## Features of ES2018 + +ES2018 introduced several new features and enhancements to JavaScript. Some of the key features of ES2018 are: + +1. **Asynchronous Iteration**: ES2018 introduced asynchronous iteration, which allows you to iterate over asynchronous data sources such as asynchronous generators and asynchronous iterators. You can use the `for-await-of` loop to iterate over asynchronous data sources. + + For example: + + ```javascript title="Asynchronous Iteration Example" + async function* asyncGenerator() { + yield 1; + yield 2; + yield 3; + } + + (async () => { + for await (let num of asyncGenerator()) { + console.log(num); + } + })(); + ``` + +2. **Promise.prototype.finally()**: ES2018 introduced the `Promise.prototype.finally()` method, which allows you to run cleanup logic after a `Promise` is settled (either fulfilled or rejected). The `finally()` method is called when the `Promise` is settled, regardless of whether it was fulfilled or rejected. + + For example: + + ```javascript title="Promise.prototype.finally() Example" + let promise = new Promise((resolve, reject) => { + resolve("Success!"); + }); + + promise.then((value) => { + console.log(value); + }).catch((error) => { + console.error(error); + }).finally(() => { + console.log("Cleanup logic here"); + }); + ``` + +3. **Rest/Spread Properties**: ES2018 introduced the rest and spread properties for object literals. The rest properties allow you to extract the remaining properties of an object into a new object, while the spread properties allow you to spread the properties of an object into another object. + + For example: + + ```js title="Rest/Spread Properties Example" + let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; + console.log(x); // Output: 1 + console.log(y); // Output: 2 + console.log(z); // Output: { a: 3, b: 4 } + ``` + +4. **Object Rest/Spread Properties**: ES2018 also introduced rest and spread properties for object destructuring. The rest properties allow you to extract the remaining properties of an object into a new object, while the spread properties allow you to spread the properties of an object into another object. + + For example: + + ```js title="Object Rest/Spread Properties Example" + let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 }; + console.log(x); // Output: 1 + console.log(y); // Output: 2 + console.log(z); // Output: { a: 3, b: 4 } + ``` + +5. **RegExp Lookbehind Assertions**: ES2018 introduced lookbehind assertions for regular expressions. Lookbehind assertions allow you to match a pattern only if it is preceded by another pattern. + + For example: + + ```js title="RegExp Lookbehind Assertions Example" + let str = "Hello, World!"; + let regex = /(?<=Hello, )World/; + console.log(regex.test(str)); // Output: true + ``` + +6. **RegExp Unicode Property Escapes**: ES2018 introduced Unicode property escapes for regular expressions. Unicode property escapes allow you to match characters based on their Unicode properties. + + For example: + + ```js title="RegExp Unicode Property Escapes Example" + let str = "๐Ÿ˜€"; + let regex = /\p{Emoji}/u; + console.log(regex.test(str)); // Output: true + ``` + +## Browser Support for ES2018 + +Most modern web browsers support ES2018 features, but some older browsers may not fully support all ES2018 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2018 code into ES5 code, which is compatible with older browsers. + +ES2018 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2018 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 66+ | | 58+ | | 11.1+ | | 79+ | | 53+ | | No | | +| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โŒ| | + +:::info ๐Ÿ“ Note + +- **Chrome**: 66+ (Latest โœ…) + + Chrome has full support for ES2018 features. You can use ES2018 features in Chrome without any issues. Chrome 66 and later versions fully support ES2018 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 58+ (Latest โœ…) + + Firefox has full support for ES2018 features. You can use ES2018 features in Firefox without any issues. Firefox 58 and later versions fully support ES2018 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 11.1+ (Latest โœ…) + + Safari has full support for ES2018 features. You can use ES2018 features in Safari without any issues. Safari 11.1 and later versions fully support ES2018 features. Safari is a popular web browser, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 79+ (Latest โœ…) + + Edge has full support for ES2018 features. You can use ES2018 features in Edge without any issues. Edge 79 and later versions fully support ES2018 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 53+ (Latest โœ…) + + Opera has full support for ES2018 features. You can use ES2018 features in Opera without any issues. Opera 53 and later versions fully support ES2018 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No (Latest โŒ) + + Internet Explorer does not support ES2018 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2018 code into ES5 code, which is compatible with Internet Explorer. + +::: + +ES2018 introduced several new features and enhancements to JavaScript, making it more powerful and expressive. You can start using ES2018 features in your JavaScript code to take advantage of these new capabilities and improve your development workflow. + +In the next tutorial, we will learn about the ES2019 version of JavaScript and the new features introduced in ES2019. + +## Conclusion + +ES2018 introduced several new features and enhancements to JavaScript, making it easier to write asynchronous code, work with objects, manipulate strings, and work with regular expressions. You can start using ES2018 features in your JavaScript code to take advantage of these new capabilities. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2019.md b/languages-platforms/javascript/js-versions/js-2019.md new file mode 100644 index 0000000..ce189fa --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2019.md @@ -0,0 +1,85 @@ +--- +id: es2019-version-of-javascript +title: JavaScript ES2019 Version (2019) +sidebar_label: ES2019 Version (2019) +sidebar_position: 6 +tags: + [ + JavaScript, + ES2019, + ECMAScript 2019, + JavaScript ES2019, + JavaScript ES2019, + JavaScript ES2019 Version, + JavaScript ES2019 Version, + ] +description: "In this tutorial, we will learn about the ES2019 version of JavaScript, also known as ECMAScript 2019. We will discuss the new features introduced in ES2019 and how to use them in your JavaScript code." +--- + +JavaScript ES2019 (ECMAScript 2019) is the tenth major release of the JavaScript language specification. It was finalized in June 2019. ES2019 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2019 and how to use them in your JavaScript code. + +## Features of ES2019 + +ES2019 introduced several new features and enhancements to JavaScript. Some of the key features of ES2019 are: + +1. **Array.prototype.flat() and Array.prototype.flatMap()**: ES2019 introduced the `Array.prototype.flat()` and `Array.prototype.flatMap()` methods for working with nested arrays. The `flat()` method flattens a nested array to a specified depth, while the `flatMap()` method maps each element using a mapping function and then flattens the result to a depth of 1. + + For example: + + ```javascript title="Array.prototype.flat() and Array.prototype.flatMap() Example" + let nestedArray = [1, [2, [3, 4], 5]]; + console.log(nestedArray.flat()); // Output: [1, 2, [3, 4], 5] + + let array = [1, 2, 3, 4, 5]; + console.log(array.flatMap((x) => [x, x * 2])); // Output: [1, 2, 2, 4, 3, 6, 4, 8, 5, 10] + ``` + +2. **Object.fromEntries()**: ES2019 introduced the `Object.fromEntries()` method, which allows you to create an object from an iterable of key-value pairs. It takes an iterable (such as an array) of key-value pairs and returns a new object with those key-value pairs. + + For example: + + ```javascript title="Object.fromEntries() Example" + let entries = [ + ["name", "Alice"], + ["age", 30], + ]; + let person = Object.fromEntries(entries); + console.log(person); // Output: { name: 'Alice', age: 30 } + ``` + +3. **String.prototype.trimStart() and String.prototype.trimEnd()**: ES2019 introduced the `String.prototype.trimStart()` and `String.prototype.trimEnd()` methods, which allow you to trim whitespace characters from the start and end of a string, respectively. These methods are also known as `String.prototype.trimLeft()` and `String.prototype.trimRight()`. + + For example: + + ```javascript title="String.prototype.trimStart() and String.prototype.trimEnd() Example" + let str = " Hello "; + console.log(str.trimStart()); // Output: 'Hello ' + console.log(str.trimEnd()); // Output: ' Hello' + ``` + +4. **Symbol.prototype.description**: ES2019 introduced the `Symbol.prototype.description` property, which allows you to access the description of a `Symbol`. The description is the optional string that was provided when the `Symbol` was created. + + For example: + + ```javascript title="Symbol.prototype.description Example" + let sym = Symbol("foo"); + console.log(sym.description); // Output: 'foo' + ``` + +## Browser Support for ES2019 + +Most modern web browsers support ES2019 features, but some older browsers may not fully support all ES2019 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2019 code into ES5 code, which is compatible with older browsers. + +ES2019 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2019 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 73+ | | 69+ | | 12.1+ | | 79+ | | 60+ | | No | | +| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โŒ| | + + +## Conclusion + +ES2019 introduced several new features and enhancements to JavaScript, making it easier and more convenient to work with arrays, objects, strings, and symbols. By using ES2019 features, you can write more concise and expressive JavaScript code. Most modern web browsers support ES2019 features, allowing you to use them in your JavaScript code without the need for a transpiler in most cases. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2020.md b/languages-platforms/javascript/js-versions/js-2020.md new file mode 100644 index 0000000..d6fa723 --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2020.md @@ -0,0 +1,128 @@ +--- +id: es2020-version-of-javascript +title: JavaScript ES2020 Version (2020) +sidebar_label: ES2020 Version (2020) +sidebar_position: 6 +tags: [JavaScript, ES2020, ECMAScript 2020, JavaScript ES2020, JavaScript ES2020, JavaScript ES2020 Version, JavaScript ES2020 Version] +description: "In this tutorial, we will learn about the ES2020 version of JavaScript, also known as ECMAScript 2020. We will discuss the new features introduced in ES2020 and how to use them in your JavaScript code." +--- + +JavaScript ES2020 (ECMAScript 2020) is the eleventh major release of the JavaScript language specification. It was finalized in June 2020. ES2020 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2020 and how to use them in your JavaScript code. + +## Features of ES2020 + +ES2020 introduced several new features and enhancements to JavaScript. Some of the key features of ES2020 are: + +1. **BigInt**: ES2020 introduced the `BigInt` primitive type, which allows you to represent arbitrarily large integers in JavaScript. The `BigInt` type is created by appending `n` to the end of an integer literal or by calling the `BigInt()` constructor with a numeric value. + + For example: + + ```javascript title="BigInt Example" + const bigNumber = 1234567890123456789012345678901234567890n; + console.log(bigNumber); // Output: 1234567890123456789012345678901234567890n + ``` + +2. **Dynamic Import**: ES2020 introduced dynamic `import()` expressions, which allow you to dynamically import modules in JavaScript. The `import()` function returns a `Promise` that resolves to the module namespace object of the requested module. + + For example: + + ```javascript title="Dynamic Import Example" + const modulePath = './module.js'; + import(modulePath) + .then((module) => { + console.log(module.default); + }) + .catch((error) => { + console.error(error); + }); + ``` + +3. **Nullish Coalescing Operator (`??`)**: ES2020 introduced the nullish coalescing operator (`??`), which allows you to provide a default value for variables that are `null` or `undefined`. The nullish coalescing operator returns the right-hand operand when the left-hand operand is `null` or `undefined`, and otherwise returns the left-hand operand. + + For example: + + ```javascript title="Nullish Coalescing Operator Example" + const name = null; + const defaultName = name ?? 'John Doe'; + console.log(defaultName); // Output: 'John Doe' + ``` + +4. **Optional Chaining Operator (`?.`)**: ES2020 introduced the optional chaining operator (`?.`), which allows you to safely access nested properties of an object without having to check if each property exists. If a property is `null` or `undefined`, the optional chaining operator short-circuits and returns `undefined`. + + For example: + + ```javascript title="Optional Chaining Operator Example" + const user = { + name: 'Alice', + address: { + city: 'New York', + }, + }; + + console.log(user.address?.city); // Output: 'New York' + console.log(user.address?.country); // Output: undefined + ``` + +5. **Promise.allSettled()**: ES2020 introduced the `Promise.allSettled()` method, which returns a `Promise` that resolves after all the input `Promises` have settled (either fulfilled or rejected). The `Promise` returned by `Promise.allSettled()` resolves with an array of objects that describe the outcome of each `Promise`. + + For example: + + ```javascript title="Promise.allSettled() Example" + const promises = [ + Promise.resolve(1), + Promise.reject(new Error('Error!')), + Promise.resolve(3), + ]; + + Promise.allSettled(promises) + .then((results) => { + results.forEach((result) => { + console.log(result.status, result.value); + }); + }); + ``` + +## Browser Support for ES2020 + +Most modern web browsers support ES2020 features, but some older browsers may not fully support all ES2020 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2020 code into ES5 code, which is compatible with older browsers. + +ES2020 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. + +For more information on browser support for ES2020 features, you can check the table. + +| | ![Chrome](@site/static/browser-img/chrome.png)| | ![Firefox](@site/static/browser-img/firefox.png)| | ![Safari](@site/static/browser-img/safari.png)| | ![Edge](@site/static/browser-img/edge.png)| | ![Opera](@site/static/browser-img/opera.png)| | ![Internet Explorer](@site/static/browser-img/ie.png)| | +|:---:|:------:|:---:| :-----:|:---:|:------:|:---:|:------:|:---:|:------:|:--:|:------:|:--:| +| | 85+ | | 79+ | | 14+ | | 79+ | | 71+ | | No | | +| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โœ…| |Latest โŒ| | + +:::info ๐Ÿ“ Note + +- **Chrome**: 85+ (Latest โœ…) + + Chrome has full support for ES2020 features. You can use ES2020 features in Chrome without any issues. Chrome 85 and later versions fully support ES2020 features. Chrome is the most popular web browser, and it is recommended to test your JavaScript code in Chrome to ensure compatibility. + +- **Firefox**: 79+ (Latest โœ…) + + Firefox has full support for ES2020 features. You can use ES2020 features in Firefox without any issues. Firefox 79 and later versions fully support ES2020 features. Firefox is a popular web browser, and it is recommended to test your JavaScript code in Firefox to ensure compatibility. + +- **Safari**: 14+ (Latest โœ…) + + Safari has full support for ES2020 features. You can use ES2020 features in Safari without any issues. Safari 14 and later versions fully support ES2020 features. Safari is a popular web browser on macOS and iOS devices, and it is recommended to test your JavaScript code in Safari to ensure compatibility. + +- **Edge**: 79+ (Latest โœ…) + + Edge has full support for ES2020 features. You can use ES2020 features in Edge without any issues. Edge 79 and later versions fully support ES2020 features. Edge is a popular web browser, and it is recommended to test your JavaScript code in Edge to ensure compatibility. + +- **Opera**: 71+ (Latest โœ…) + + Opera has full support for ES2020 features. You can use ES2020 features in Opera without any issues. Opera 71 and later versions fully support ES2020 features. Opera is a popular web browser, and it is recommended to test your JavaScript code in Opera to ensure compatibility. + +- **Internet Explorer**: No support (Latest โŒ) + + Internet Explorer does not support ES2020 features. If you need to support Internet Explorer, you can use a transpiler like Babel to convert your ES2020 code into ES5 code, which is compatible with Internet Explorer. + +::: + +## Conclusion + +ES2020 introduced several new features and enhancements to JavaScript, such as the `BigInt` primitive type, dynamic `import()` expressions, the nullish coalescing operator (`??`), the optional chaining operator (`?.`), and the `Promise.allSettled()` method. These features improve the expressiveness and flexibility of JavaScript, making it easier to write clean and concise code. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2021.md b/languages-platforms/javascript/js-versions/js-2021.md new file mode 100644 index 0000000..348ddb2 --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2021.md @@ -0,0 +1,116 @@ +--- +id: es2021-version-of-javascript +title: JavaScript ES2021 Version (2021) +sidebar_label: ES2021 Version (2021) +sidebar_position: 7 +tags: [JavaScript, ES2021, ECMAScript 2021, JavaScript ES2021, JavaScript ES2021, JavaScript ES2021 Version, JavaScript ES2021 Version] +description: "In this tutorial, we will learn about the ES2021 version of JavaScript, also known as ECMAScript 2021. We will discuss the new features introduced in ES2021 and how to use them in your JavaScript code." +--- + +JavaScript ES2021 (ECMAScript 2021) is the twelfth major release of the JavaScript language specification. It was finalized in June 2021. ES2021 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2021 and how to use them in your JavaScript code. + +## Features of ES2021 + +ES2021 introduced several new features and enhancements to JavaScript. Some of the key features of ES2021 are: + +1. **String.prototype.replaceAll()**: ES2021 introduced the `String.prototype.replaceAll()` method, which allows you to replace all occurrences of a substring within a string with another substring. The `replaceAll()` method replaces all occurrences of a specified substring with another substring and returns a new string. + + For example: + + ```javascript title="String.prototype.replaceAll() Example" + let str = "Hello, World!"; + let newStr = str.replaceAll("o", "0"); + console.log(newStr); // Output: Hell0, W0rld! + ``` + +2. **Logical Assignment Operators**: ES2021 introduced the logical assignment operators `||=` (logical OR assignment) and `&&=` (logical AND assignment). These operators allow you to assign a value to a variable only if the variable is `null`, `undefined`, `false`, `0`, `NaN`, or an empty string (`""`). + + For example: + + ```javascript title="Logical Assignment Operators Example" + let x = 10; + x ||= 20; // Equivalent to: x = x || 20; + console.log(x); // Output: 10 + + let y = 0; + y &&= 5; // Equivalent to: y = y && 5; + console.log(y); // Output: 0 + ``` + +3. **Numeric Separators**: ES2021 introduced numeric separators, which allow you to use underscores (`_`) as separators in numeric literals to make them more readable. Numeric separators are ignored by the JavaScript engine and are used only for formatting purposes. + + For example: + + ```javascript title="Numeric Separators Example" + let billion = 1_000_000_000; + console.log(billion); // Output: 1000000000 + + let pi = 3.14159_26535; + console.log(pi); // Output: 3.1415926535 + ``` + +4. **WeakRef**: ES2021 introduced the `WeakRef` object, which allows you to create weak references to objects. Weak references do not prevent the garbage collector from collecting the object they reference. The `WeakRef` object is useful for implementing caches or other data structures that need to hold references to objects without preventing them from being garbage collected. + + For example: + + ```javascript title="WeakRef Example" + let obj = { name: "Alice" }; + let weakRef = new WeakRef(obj); + console.log(weakRef.deref()); // Output: { name: 'Alice' } + ``` + +5. **FinalizationRegistry**: ES2021 introduced the `FinalizationRegistry` object, which allows you to register objects for cleanup when they are garbage collected. The `FinalizationRegistry` object is used to perform cleanup actions on objects before they are collected by the garbage collector. + + For example: + + ```javascript title="FinalizationRegistry Example" + let obj = { name: "Alice" }; + let finalizationRegistry = new FinalizationRegistry((heldValue) => { + console.log(`Cleaning up: ${heldValue.name}`); + }); + finalizationRegistry.register(obj, "held value"); + obj = null; // Allow obj to be garbage collected + ``` + +6. **Promise.any()**: ES2021 introduced the `Promise.any()` method, which takes an iterable of `Promises` and returns a new `Promise` that resolves as soon as one of the input `Promises` is fulfilled. If all the input `Promises` are rejected, the `Promise` returned by `Promise.any()` is rejected with an `AggregateError` that contains an array of rejection reasons. + + For example: + + ```javascript title="Promise.any() Example" + const promises = [ + Promise.reject("Error 1"), + Promise.resolve("Success 1"), + Promise.reject("Error 2"), + ]; + + Promise.any(promises) + .then((value) => { + console.log(value); // Output: "Success 1" + }) + .catch((error) => { + console.error(error); // Output: AggregateError: All promises were rejected + }); + ``` + +7. **AggregateError**: ES2021 introduced the `AggregateError` object, which is used to represent multiple errors in a single error object. The `AggregateError` object contains an array of errors as its `errors` property. + + For example: + + ```javascript title="AggregateError Example" + const error1 = new Error("Error 1"); + const error2 = new Error("Error 2"); + const aggregateError = new AggregateError([error1, error2]); + console.log(aggregateError.errors); // Output: [Error: Error 1, Error: Error 2] + ``` + +## Browser Support for ES2021 + +Most modern web browsers support ES2021 features, but some older browsers may not fully support all ES2021 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2021 code into ES5 code, which is compatible with older browsers. + +ES2021 features are generally well-supported in modern web browsers, and you can start using them in your JavaScript code without the need for a transpiler in most cases. However, it is always a good practice to check the compatibility of the features you are using with the target browsers to ensure a consistent user experience. + +For more information on browser support for ES2021 features, you can check the compatibility tables provided by [Can I use](https://caniuse.com/). + +## Conclusion + +In this tutorial, we learned about the ES2021 version of JavaScript (ECMAScript 2021) and the new features introduced in ES2021. We explored features such as `String.prototype.replaceAll()`, logical assignment operators, numeric separators, `WeakRef`, `FinalizationRegistry`, `Promise.any()`, and `AggregateError`. You can start using these features in your JavaScript code to take advantage of the latest enhancements in the language. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2022.md b/languages-platforms/javascript/js-versions/js-2022.md new file mode 100644 index 0000000..69b74f0 --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2022.md @@ -0,0 +1,126 @@ +--- +id: es2022-version-of-javascript +title: JavaScript ES2022 Version (2022) +sidebar_label: ES2022 Version (2022) +sidebar_position: 8 +tags: [JavaScript, ES2022, ECMAScript 2022, JavaScript ES2022, JavaScript ES2022, JavaScript ES2022 Version, JavaScript ES2022 Version] +description: "In this tutorial, we will learn about the ES2022 version of JavaScript, also known as ECMAScript 2022. We will discuss the new features introduced in ES2022 and how to use them in your JavaScript code." +--- + +JavaScript ES2022 (ECMAScript 2022) is the thirteenth major release of the JavaScript language specification. It was finalized in June 2022. ES2022 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2022 and how to use them in your JavaScript code. + +## Features of ES2022 + +ES2022 introduced several new features and enhancements to JavaScript. Some of the key features of ES2022 are: + +1. **String.prototype.replaceAll()**: ES2022 introduced the `String.prototype.replaceAll()` method, which allows you to replace all occurrences of a substring within a string with another substring. The `replaceAll()` method replaces all occurrences of a specified substring with another substring and returns a new string. + + For example: + + ```javascript title="String.prototype.replaceAll() Example" + let str = "Hello, World!"; + let newStr = str.replaceAll("o", "0"); + console.log(newStr); // Output: Hell0, W0rld! + ``` + +2. **Logical Assignment Operators**: ES2022 introduced the logical assignment operators `||=` (logical OR assignment) and `&&=` (logical AND assignment). These operators allow you to assign a value to a variable only if the variable is `null`, `undefined`, `false`, `0`, `NaN`, or an empty string (`""`). + + For example: + + ```javascript title="Logical Assignment Operators Example" + let x = 10; + x ||= 20; // Equivalent to: x = x || 20; + console.log(x); // Output: 10 + + let y = 0; + y &&= 5; // Equivalent to: y = y && 5; + console.log(y); // Output: 0 + ``` + +3. **Numeric Separators**: ES2022 introduced numeric separators, which allow you to use underscores (`_`) as separators in numeric literals to make them more readable. Numeric separators are ignored by the JavaScript engine and are used only for formatting purposes. + + For example: + + ```javascript title="Numeric Separators Example" + let billion = 1_000_000_000; + console.log(billion); // Output: 1000000000 + + let pi = 3.14159_26535; + console.log(pi); // Output: 3.1415926535 + ``` + +4. **WeakRef**: ES2022 introduced the `WeakRef` object, which allows you to create weak references to objects. Weak references do not prevent the garbage collector from collecting the object they reference. The `WeakRef` object is useful for implementing caches or other data structures that need to hold references to objects without preventing them from being garbage collected. + + For example: + + ```javascript title="WeakRef Example" + let obj = { name: "Alice" }; + let weakRef = new WeakRef(obj); + console.log(weakRef.deref()); // Output: { name: 'Alice' } + ``` + +5. **Promise.any()**: ES2022 introduced the `Promise.any()` method, which takes an iterable of `Promise` objects and returns a single `Promise` that fulfills with the value of the first `Promise` in the iterable that fulfills. If all `Promise` objects in the iterable are rejected, the `Promise` returned by `Promise.any()` is rejected with an `AggregateError` containing the rejection reasons. + + For example: + + ```javascript title="Promise.any() Example" + let promise1 = new Promise((resolve, reject) => setTimeout(() => reject("Error 1"), 1000)); + let promise2 = new Promise((resolve, reject) => setTimeout(() => resolve("Success 2"), 500)); + let promise3 = new Promise((resolve, reject) => setTimeout(() => reject("Error 3"), 1500); + + Promise.any([promise1, promise2, promise3]) + .then((value) => console.log(value)) + .catch((error) => console.error(error)); + ``` + +6. **Final State**: ES2022 introduced the `final` keyword, which can be used to declare a variable as a constant that cannot be reassigned. The `final` keyword is similar to the `const` keyword but enforces immutability more strictly. + + For example: + + ```java title="Final State Example" + final int x = 10; + x = 20; // Error: Cannot assign a value to a final variable + ``` + +7. **Record and Tuple**: ES2022 introduced the `record` and `tuple` types, which are new built-in types in JavaScript. The `record` type is an object type with a fixed set of properties, while the `tuple` type is an array type with a fixed number of elements and element types. + + For example: + + ```javascript title="Record and Tuple Example" + let person: record { name: string, age: number } = { name: "Alice", age: 30 }; + let pair: tuple [string, number] = ["Alice", 30]; + ``` + +8. **Private Fields**: ES2022 introduced private fields, which allow you to define private instance fields in classes. Private fields are not accessible from outside the class and are intended for internal use within the class. + + For example: + + ```javascript title="Private Fields Example" + class Person { + #name; + + constructor(name) { + this.#name = name; + } + + getName() { + return this.#name; + } + } + + let person = new Person("Alice"); + console.log(person.#name); // Error: Private field '#name' is not accessible outside class 'Person' + console.log(person.getName()); // Output: 'Alice' + ``` + +## Browser Support for ES2022 + +Most modern web browsers support ES2022 features, but some older browsers may not fully support all ES2022 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES2022 code into ES5 code, which is compatible with older browsers. + +In this tutorial, we learned about the new features introduced in the ES2022 version of JavaScript (ECMAScript 2022) and how to use them in your JavaScript code. ES2022 introduced several new features and enhancements to JavaScript, such as `String.prototype.replaceAll()`, logical assignment operators, numeric separators, `WeakRef`, `Promise.any()`, `final` keyword, `record` and `tuple` types, and private fields. These features can help you write more expressive and efficient JavaScript code. + +You can start using these features in your JavaScript code to take advantage of the latest enhancements in the language. For more information on browser support for ES2022 features, you can check the compatibility tables provided by [Can I use](https://caniuse.com/). + +## Conclusion + +ES2022 introduced several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we learned about the new features introduced in ES2022, such as `String.prototype.replaceAll()`, logical assignment operators, numeric separators, `WeakRef`, `Promise.any()`, `final` keyword, `record` and `tuple` types, and private fields. These features can help you write more expressive and efficient JavaScript code. You can start using these features in your JavaScript code to take advantage of the latest enhancements in the language. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-2023.md b/languages-platforms/javascript/js-versions/js-2023.md new file mode 100644 index 0000000..36a514f --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-2023.md @@ -0,0 +1,10 @@ +--- +id: es2023-version-of-javascript +title: JavaScript ES2023 Version (2023) +sidebar_label: ES2023 Version (2023) +sidebar_position: 9 +tags: [JavaScript, ES2023, ECMAScript 2023, JavaScript ES2023, JavaScript ES2023, JavaScript ES2023 Version, JavaScript ES2023 Version] +description: "In this tutorial, we will learn about the ES2023 version of JavaScript, also known as ECMAScript 2023. We will discuss the new features introduced in ES2023 and how to use them in your JavaScript code." +--- + +JavaScript ES2023 (ECMAScript 2023) is the twelfth major release of the JavaScript language specification. It is expected to be finalized in June 2023. ES2023 is expected to introduce several new features and enhancements to JavaScript, building upon the foundation laid by ES6 (ES2015). In this tutorial, we will learn about the new features introduced in ES2023 and how to use them in your JavaScript code. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-es5.md b/languages-platforms/javascript/js-versions/js-es5.md new file mode 100644 index 0000000..d118439 --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-es5.md @@ -0,0 +1,233 @@ +--- +id: es5-version-of-javascript +title: ES5 Version of JavaScript +sidebar_label: ES5 Version (2009) +sidebar_position: 1 +tags: [JavaScript, ES5, ES5 Version of JavaScript, ES5 JavaScript, ES5 JavaScript Tutorial, ES5 JavaScript Example, ES5 JavaScript Features, ES5 JavaScript Improvements, ES5 JavaScript Development, ES5 JavaScript Changes, ES5 JavaScript New Features, ES5 JavaScript Tutorial for Beginners, ES5 JavaScript Tutorial for Developers, ES5 JavaScript Tutorial Example, ES5 JavaScript Tutorial Features, ES5 JavaScript Tutorial Improvements, ES5 JavaScript Tutorial Changes, ES5 JavaScript Tutorial New Features, ES5 JavaScript Tutorial Development, ES5 JavaScript Tutorial Beginners, ES5 JavaScript Tutorial Developers, ES5 JavaScript Tutorial Example, ES5 JavaScript Tutorial Features, ES5 JavaScript Tutorial Improvements, ES5 JavaScript Tutorial Changes, ES5 JavaScript Tutorial New Features, ES5 JavaScript Tutorial Development] +description: "In this tutorial, we will learn about the ES5 version of JavaScript, which was released in 2009. We will explore the new features and improvements introduced in ES5 and how they have impacted JavaScript development." +--- + +JavaScript ES5 (ECMAScript 5) is the fifth edition of the ECMAScript standard, which was released in 2009. It introduced several new features and improvements to the language, making it more powerful and flexible for developers. In this tutorial, we will learn about the ES5 version of JavaScript and how it has impacted JavaScript development. + +## Features of ES5 + +### Strict Mode + +One of the key features introduced in ES5 is strict mode. Strict mode is a special mode that allows you to opt into a restricted variant of JavaScript that enforces stricter parsing and error handling. It helps you write more secure and optimized code by catching common coding mistakes and preventing certain actions that are considered bad practice. + +To enable strict mode in your code, you can add the following directive at the beginning of your script: + +```javascript title="Strict Mode in ES5" +"use strict"; + +function myFunction() { + console.log("This is a strict mode function"); +} + +myFunction(); +``` + +By using strict mode, you can avoid common pitfalls in JavaScript and write cleaner, more reliable code. + +### `JSON` Object + +ES5 introduced the `JSON` object, which provides methods for parsing and serializing JSON data. The `JSON` object includes two main methods: + +- `JSON.parse()`: Parses a JSON string and returns a JavaScript object. +- `JSON.stringify()`: Converts a JavaScript object into a JSON string. + - This method is useful for serializing data before sending it to a server or storing it in a database. + - It can also be used to pretty-print JSON data for debugging purposes. + - The `JSON.stringify()` method can take an optional `replacer` function or an array of properties to include or exclude from the serialization process. + - It can also take an optional `space` parameter to specify the indentation level for the output JSON string. + - The `JSON.stringify()` method can handle circular references by throwing an error or replacing the circular reference with a placeholder value. +- The `JSON` object also includes the `JSON.parse()` method, which can parse a JSON string and return a JavaScript object. +- The `JSON.parse()` method can take an optional `reviver` function to transform the parsed data before returning it. +- The `JSON.parse()` method can handle invalid JSON strings by throwing a `SyntaxError` or returning `null`. +- The `JSON.parse()` method can also handle duplicate keys by throwing a `SyntaxError` or using the last key-value pair encountered. + +Here is an example of using the `JSON` object to parse and stringify JSON data: + +```javascript title="JSON Object in ES5" +// Parsing JSON data +const jsonString = '{"name": "John", "age": 30}'; +const data = JSON.parse(jsonString); + +console.log(data.name); // John +console.log(data.age); // 30 + +// Stringifying JavaScript object +const person = { name: "Alice", age: 25 }; +const jsonData = JSON.stringify(person); + +console.log(jsonData); // {"name":"Alice","age":25} +``` + +### `Array` Methods + +ES5 introduced several new methods for the `Array` object, making it easier to work with arrays in JavaScript. Some of the key methods introduced in ES5 include: + +- `Array.prototype.forEach()`: Executes a provided function once for each array element. +- `Array.prototype.map()`: Creates a new array with the results of calling a provided function on every element in the array. +- `Array.prototype.filter()`: Creates a new array with all elements that pass a test implemented by the provided function. +- `Array.prototype.reduce()`: Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. +- `Array.prototype.some()`: Tests whether at least one element in the array passes the test implemented by the provided function. +- `Array.prototype.every()`: Tests whether all elements in the array pass the test implemented by the provided function. +- `Array.prototype.indexOf()`: Returns the first index at which a given element can be found in the array. +- `Array.prototype.lastIndexOf()`: Returns the last index at which a given element can be found in the array. +- `Array.prototype.reduceRight()`: Applies a function against an accumulator and each element in the array (from right to left) to reduce it to a single value. +- `Array.prototype.forEach()`: Executes a provided function once for each array element. +- `Array.prototype.map()`: Creates a new array with the results of calling a provided function on every element in the array. + +Here is an example of using the `Array` methods introduced in ES5: + +```javascript title="Array Methods in ES5" +const numbers = [1, 2, 3, 4, 5]; + +// Using forEach + +numbers.forEach((number) => { + console.log(number); +}); + +// Using map + +const doubledNumbers = numbers.map((number) => number * 2); +console.log(doubledNumbers); // [2, 4, 6, 8, 10] + +// Using filter + +const evenNumbers = numbers.filter((number) => number % 2 === 0); +console.log(evenNumbers); // [2, 4] + +// Using reduce + +const sum = numbers.reduce((accumulator, number) => accumulator + number, 0); +console.log(sum); // 15 +``` + +### `Function.prototype.bind()` + +ES5 introduced the `Function.prototype.bind()` method, which allows you to create a new function with a specified `this` value and initial arguments. This method is useful for creating functions with a fixed context, which can be helpful when working with event handlers or callbacks. + +Here is an example of using the `Function.prototype.bind()` method: + +```javascript title="Function.prototype.bind() in ES5" +const person = { + name: "Alice", + greet: function() { + console.log(`Hello, my name is ${this.name}`); + }, +}; + +const greetFunction = person.greet; +greetFunction(); // Hello, my name is undefined + +const boundGreetFunction = person.greet.bind(person); +boundGreetFunction(); // Hello, my name is Alice +``` + +### Getters and Setters + +ES5 introduced support for getters and setters in JavaScript objects. Getters are used to get the value of a property, while setters are used to set the value of a property. Getters and setters allow you to define computed properties and control access to object properties. + +Here is an example of using getters and setters in ES5: + +```javascript title="Getters and Setters in ES5" +const person = { + firstName: "John", + lastName: "Doe", + get fullName() { + return `${this.firstName} ${this.lastName}`; + }, + set fullName(value) { + const parts = value.split(" "); + this.firstName = parts[0]; + this.lastName = parts[1]; + }, +}; + +console.log(person.fullName); // John Doe + +person.fullName = "Alice Smith"; +console.log(person.firstName); // Alice +console.log(person.lastName); // Smith +``` + +### `Object.keys()` + +ES5 introduced the `Object.keys()` method, which returns an array of a given object's own enumerable property names. This method is useful for iterating over the properties of an object and accessing their values. + +Here is an example of using the `Object.keys()` method in ES5: + +```javascript title="Object.keys() in ES5" +const person = { + name: "John", + age: 30, +}; + +const keys = Object.keys(person); +console.log(keys); // ["name", "age"] + +keys.forEach((key) => { + console.log(`${key}: ${person[key]}`); +}); +``` + +### `Array.isArray()` + +ES5 introduced the `Array.isArray()` method, which checks whether a given value is an array. This method is useful for determining the type of a value and handling it accordingly. + +Here is an example of using the `Array.isArray()` method in ES5: + +```javascript title="Array.isArray() in ES5" +const numbers = [1, 2, 3, 4, 5]; + +console.log(Array.isArray(numbers)); // true + +const person = { + name: "Alice", + age: 25, +}; + +console.log(Array.isArray(person)); // false +``` + +## Browser Support for ES5 + +ES5 is supported by all modern web browsers, including Chrome, Firefox, Safari, Edge, and Opera. It is also supported by Internet Explorer 9 and later versions. Since ES5 was released in 2009, it is widely adopted and compatible with most web development environments. + +By using ES5 features in your JavaScript code, you can ensure better compatibility with a wide range of browsers and devices. ES5 provides a solid foundation for building web applications and enables you to write more efficient and maintainable code. + +### Compatibility Table for ES5 + +Here is a compatibility table showing the support for ES5 features in modern web browsers: + +| Feature | Chrome | Firefox | Safari | Edge | Opera | IE | +|-----------------------|--------|---------|--------|------|-------|-------| +| Strict Mode | 5 | 4 | 5 | 12 | 12 | 9 | +| `JSON` Object | 3 | 3.5 | 4 | 8 | 10.5 | 8 | +| `Array` Methods | 5 | 4 | 5 | 12 | 12 | 9 | +| `Function.prototype.bind()` | 7 | 4 | 5 | 12 | 12 | 9 | +| Getters and Setters | 3 | 2 | 5 | 12 | 12 | 9 | +| `Object.keys()` | 5 | 4 | 5 | 12 | 12 | 9 | +| `Array.isArray()` | 5 | 4 | 5 | 12 | 12 | 9 | +| `Array.prototype.forEach()` | 1 | 1.5 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.map()` | 1 | 1.5 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.filter()` | 1 | 1.5 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.reduce()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.some()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.every()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.indexOf()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.lastIndexOf()` | 1 | 3 | 5 | 12 | 10.5 | 9 | +| `Array.prototype.reduceRight()` | 1 | 3 | 5 | 12 | 10.5 | 9 | + +:::info Note +The version numbers in the compatibility table represent the first stable release of the browser that supports the feature. For example, Chrome 5 indicates that the feature is supported in Chrome version 5 and later. + +> The version numbers in the compatibility table represent the first stable version that supports the feature. The compatibility data is based on [Can I use](https://caniuse.com/) and [MDN Web Docs](https://developer.mozilla.org/). + +::: + +## Conclusion + +In this tutorial, we learned about the ES5 version of JavaScript, which introduced several new features and improvements to the language. We explored the key features of ES5, including strict mode, the `JSON` object, new `Array` methods, `Function.prototype.bind()`, getters and setters, `Object.keys()`, and `Array.isArray()`. We also discussed the browser support for ES5 and how it has impacted JavaScript development. By understanding the features of ES5, you can write more efficient and maintainable JavaScript code for your web applications. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-es6.md b/languages-platforms/javascript/js-versions/js-es6.md new file mode 100644 index 0000000..39dea7d --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-es6.md @@ -0,0 +1,83 @@ +--- +id: es6-version-of-javascript +title: ES6 Version in JavaScript +sidebar_label: ES6 Version (2015) +sidebar_position: 2 +tags: [JavaScript, ES6, ES2015, ES6 Version, ECMAScript 6, ECMAScript 2015, JavaScript ES6, JavaScript ES2015, JavaScript ES6 Version, JavaScript ES2015 Version] +description: "In this tutorial, we will learn about the ES6 version of JavaScript, also known as ECMAScript 6 or ECMAScript 2015. We will discuss the new features introduced in ES6 and how to use them in your JavaScript code." +--- + +JavaScript ES6 (ECMAScript 6) is the sixth major release of the JavaScript language specification. It was finalized in June 2015. ES6 introduced many new features and syntax enhancements to JavaScript, making it more powerful and expressive. In this tutorial, we will learn about the new features introduced in ES6 and how to use them in your JavaScript code. + +## Features of ES6 + +ES6 introduced several new features and enhancements to JavaScript. Some of the key features of ES6 are: + +1. **`let` and `const` Declarations**: ES6 introduced two new ways to declare variables in JavaScript: `let` and `const`. The `let` keyword is used to declare block-scoped variables, while the `const` keyword is used to declare variables whose values cannot be reassigned. +2. **Arrow Functions**: Arrow functions are a new way to define functions in JavaScript. They provide a more concise syntax for writing function expressions. +3. **Template Literals**: Template literals are a new way to define strings in JavaScript. They allow you to embed expressions and variables inside a string using `${}`. +4. **Destructuring Assignment**: Destructuring assignment allows you to extract values from arrays or objects and assign them to variables in a single statement. +5. **Spread and Rest Operators**: ES6 introduced the spread (`...`) and rest (`...`) operators. The spread operator allows you to expand an array or object into individual elements, while the rest operator allows you to collect multiple elements into an array or object. +6. **Classes**: ES6 introduced a new way to define classes in JavaScript using the `class` keyword. Classes provide a more familiar and concise syntax for defining object-oriented programming concepts. +7. **Modules**: ES6 introduced a new module system for JavaScript using the `import` and `export` keywords. Modules allow you to split your code into multiple files and import/export functionality between them. +8. **Promises**: Promises are a new way to work with asynchronous code in JavaScript. They provide a cleaner and more readable syntax for handling asynchronous operations. +9. **Generators**: Generators are a new type of function in JavaScript that can be paused and resumed. They are useful for writing asynchronous code in a synchronous style. +10. **Default Parameters**: ES6 introduced default parameter values for functions. Default parameters allow you to specify default values for function parameters if no value is provided. +11. **Enhanced Object Literals**: ES6 introduced several enhancements to object literals, such as shorthand property and method definitions, computed property names, and method definition shorthand. +12. **Map and Set Data Structures**: ES6 introduced two new data structures: `Map` and `Set`. `Map` is a collection of key-value pairs, while `Set` is a collection of unique values. +13. **Symbols**: Symbols are a new primitive data type in JavaScript introduced in ES6. They are unique and immutable values that can be used as object keys. +14. **Iterators and Iterables**: ES6 introduced the concept of iterators and iterables. Iterators are objects that define a sequence of values, while iterables are objects that can be iterated over using the `for...of` loop. +15. **Typed Arrays**: ES6 introduced a new way to work with binary data in JavaScript using typed arrays. Typed arrays allow you to work with raw binary data in a more efficient way. +16. **New String Methods**: ES6 introduced several new methods for working with strings, such as `startsWith()`, `endsWith()`, `includes()`, and `repeat()`. +17. **New Array Methods**: ES6 introduced several new methods for working with arrays, such as `find()`, `findIndex()`, `some()`, and `every()`. +18. **New Number Methods**: ES6 introduced several new methods for working with numbers, such as `isFinite()`, `isNaN()`, and `isInteger()`. +19. **New Math Methods**: ES6 introduced several new methods for working with mathematical operations, such as `Math.sign()`, `Math.trunc()`, and `Math.cbrt()`. +20. **New Object Methods**: ES6 introduced several new methods for working with objects, such as `Object.assign()`, `Object.keys()`, `Object.values()`, and `Object.entries()`. +21. **New Reflect API**: ES6 introduced a new set of reflection methods for working with objects, such as `Reflect.get()`, `Reflect.set()`, and `Reflect.construct()`. +22. **New Proxy API**: ES6 introduced a new set of proxy methods for creating and handling proxies, which are objects that intercept and customize the behavior of fundamental operations on other objects. +23. **Internationalization and Localization**: ES6 introduced new features for working with internationalization and localization, such as the `Intl` object and the `Intl.Collator`, `Intl.DateTimeFormat`, and `Intl.NumberFormat` classes. +24. **Tail Call Optimization**: ES6 introduced tail call optimization, which allows JavaScript engines to optimize recursive functions that are tail calls, making them more memory-efficient. +25. **Other Features**: ES6 introduced many other features and enhancements, such as binary and octal literals, new syntax for promises, and new syntax for regular expressions. + +## Browser Support for ES6 + +Most modern web browsers support ES6 features, but some older browsers may not fully support all ES6 features. To ensure that your JavaScript code works across all browsers, you can use a transpiler like Babel to convert your ES6 code into ES5 code, which is compatible with older browsers. + +## Using ES6 Features + +To use ES6 features in your JavaScript code, you can write your code using ES6 + +```javascript title="ES6 Code Example" +// ES6 code +const greet = (name) => { + return `Hello, ${name}!`; +}; + +console.log(greet("Alice")); +``` + +You can also use a transpiler like Babel to convert your ES6 code into ES5 code. To do this, you can install Babel using + +```bash npm2yarn +npm install --save-dev @babel/core @babel/cli @babel/preset-env +``` + +Then, you can create a `.babelrc` file in your project directory with the following configuration + +```json title=".babelrc" +{ + "presets": ["@babel/preset-env"] +} +``` + +Finally, you can transpile your ES6 code into ES5 code using + +```bash title="Transpile ES6 to ES5 using Babel" +npx babel src --out-dir dist +``` + +By using Babel, you can write modern ES6 code and ensure that it works across all browsers. + +## Conclusion + +ES6 introduced many new features and enhancements to JavaScript, making it more powerful and expressive. In this tutorial, we learned about the key features of ES6 and how to use them in your JavaScript code. By using ES6 features, you can write cleaner, more readable, and more maintainable JavaScript code. \ No newline at end of file diff --git a/languages-platforms/javascript/js-versions/js-history.md b/languages-platforms/javascript/js-versions/js-history.md new file mode 100644 index 0000000..11e58db --- /dev/null +++ b/languages-platforms/javascript/js-versions/js-history.md @@ -0,0 +1,96 @@ +--- +id: javascript-history +title: JavaScript Versions History +sidebar_label: JS History +sidebar_position: 10 +tags: [JavaScript, JavaScript Versions, ECMAScript, JavaScript History, JavaScript Versions History] +description: "In this tutorial, we will explore the history of JavaScript versions, starting from the initial release in 1995 to the latest version. We will discuss the key features introduced in each version and the evolution of the JavaScript language over the years." +--- + +JavaScript is a versatile and powerful programming language that has evolved significantly since its inception in 1995. Over the years, JavaScript has undergone several major revisions, introducing new features and enhancements to the language. In this tutorial, we will explore the history of JavaScript versions, starting from the initial release in 1995 to the latest version. We will discuss the key features introduced in each version and the evolution of the JavaScript language over the years. + +## JavaScript Versions + +### 1. JavaScript 1.0 (1995) + +JavaScript was first introduced in 1995 by Brendan Eich at Netscape Communications. The initial version of JavaScript, known as JavaScript 1.0, was released in the same year. JavaScript 1.0 included the core features of the language, such as variables, functions, loops, and conditional statements. + +### 2. JavaScript 1.1 (1996) + +JavaScript 1.1 was released in 1996 and introduced several new features, including support for regular expressions, better error handling, and improved performance. This version also added support for the `let` statement and the `const` statement for declaring variables. + +### 3. JavaScript 1.2 (1997) + +JavaScript 1.2 was released in 1997 and introduced several new features, such as support for `do-while` loops, the `switch` statement, and the `for-in` loop. This version also added support for the `eval()` function for evaluating JavaScript code dynamically. + +### 4. JavaScript 1.3 (1998) + +JavaScript 1.3 was released in 1998 and introduced several new features, including support for regular expressions, better error handling, and improved performance. This version also added support for the `let` statement and the `const` statement for declaring variables. + +### 5. JavaScript 1.4 (1999) + +JavaScript 1.4 was released in 1999 and introduced several new features, such as support for `do-while` loops, the `switch` statement, and the `for-in` loop. This version also added support for the `eval()` function for evaluating JavaScript code dynamically. + +### 6. JavaScript 1.5 (2000) + +JavaScript 1.5 was released in 2000 and introduced several new features, including support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 7. JavaScript 1.6 (2005) + +JavaScript 1.6 was released in 2005 and introduced several new features, such as support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 8. JavaScript 1.7 (2006) + +JavaScript 1.7 was released in 2006 and introduced several new features, such as support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 9. JavaScript 1.8 (2008) + +JavaScript 1.8 was released in 2008 and introduced several new features, such as support for array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 10. ECMAScript 5 (2009) + +ECMAScript 5 was released in 2009 and introduced several new features, such as strict mode, JSON support, and array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 11. ECMAScript 5.1 (2011) + +ECMAScript 5.1 was released in 2011 and introduced several new features, such as strict mode, JSON support, and array methods such as `forEach()`, `map()`, `filter()`, and `reduce()`. This version also added support for the `Function.prototype.bind()` method for binding the `this` value in functions. + +### 12. ECMAScript 6 (ES2015) + +ECMAScript 6, also known as ES2015, was released in 2015 and introduced several new features, such as arrow functions, classes, modules, template literals, and destructuring assignments. This version also added support for the `let` statement and the `const` statement for declaring variables. + +### 13. ECMAScript 7 (ES2016) + +ECMAScript 7, also known as ES2016, was released in 2016 and introduced several new features, such as the `includes()` method for arrays, the `**` operator for exponentiation, and the `async` and `await` keywords for handling asynchronous operations. + +### 14. ECMAScript 8 (ES2017) + +ECMAScript 8, also known as ES2017, was released in 2017 and introduced several new features, such as the `Object.values()` method, the `Object.entries()` method, and the `String.prototype.padStart()` and `String.prototype.padEnd()` methods for padding strings. + +### 15. ECMAScript 9 (ES2018) + +ECMAScript 9, also known as ES2018, was released in 2018 and introduced several new features, such as asynchronous iteration, the `Promise.prototype.finally()` method, and rest/spread properties for object literals and destructuring. + +### 16. ECMAScript 10 (ES2019) + +ECMAScript 10, also known as ES2019, was released in 2019 and introduced several new features, such as `Array.prototype.flat()` and `Array.prototype.flatMap()` methods, the `Object.fromEntries()` method, and the `String.prototype.trimStart()` and `String.prototype.trimEnd()` methods. + +### 17. ECMAScript 11 (ES2020) + +ECMAScript 11, also known as ES2020, was released in 2020 and introduced several new features, such as the `BigInt` data type for working with arbitrary precision integers, the `Promise.allSettled()` method, and the `String.prototype.matchAll()` method for working with regular expressions. + +### 18. ECMAScript 12 (ES2021) + +ECMAScript 12, also known as ES2021, was released in 2021 and introduced several new features, such as the `String.prototype.replaceAll()` method for replacing all occurrences of a substring, the `Logical Assignment Operators` for combining logical operations with assignment, and the `Numeric Separators` for improving the readability of numeric literals. + +### 19. ECMAScript 13 (ES2022) + +ECMAScript 13, also known as ES2022, was released in 2022 and introduced several new features, such as the `Array.prototype.groupBy()` method for grouping array elements based on a key, the `String.prototype.sliceSet()` method for replacing a slice of a string with another string, and the `Object.hasOwn()` method for checking if an object has a property. + +### 20. ECMAScript 14 (ES2023) + +ECMAScript 14, also known as ES2023, is the upcoming version of JavaScript that is expected to be released in 2023. It is expected to introduce several new features and enhancements to the language, building upon the foundation laid by previous versions. + +## Conclusion + +In this tutorial, we explored the history of JavaScript versions, starting from the initial release in 1995 to the latest version. We discussed the key features introduced in each version and the evolution of the JavaScript language over the years. JavaScript has come a long way since its inception and continues to evolve to meet the changing needs of developers and the web platform. \ No newline at end of file diff --git a/languages-platforms/javascript/json-js.md b/languages-platforms/javascript/json-js.md new file mode 100644 index 0000000..0fdc16c --- /dev/null +++ b/languages-platforms/javascript/json-js.md @@ -0,0 +1,346 @@ +--- +id: json-in-javascript +title: JSON in JavaScript +sidebar_label: JSON +sidebar_position: 38 +tags: + [ + JavaScript, + JSON, + json-in-javascript, + json, + javascript-json, + javascript-json-tutorial, + json-tutorial, + json-in-javascript-tutorial, + json-in-javascript-example, + json-in-javascript-syntax, + json-in-javascript-usage, + json-in-javascript-usage-example, + json-in-javascript-usage-syntax, + json-in-javascript-usage-guide, + json-in-javascript-guide, + json-in-javascript-example, + json-in-javascript-example-guide, + json-in-javascript-example-tutorial, + json-in-javascript-tutorial-guide, + json-in-javascript-tutorial-example, + json-in-javascript-tutorial-syntax, + json-in-javascript-tutorial-usage, + json-in-javascript-tutorial-example-guide, + json-in-javascript-tutorial-usage-example, + json-in-javascript-tutorial-syntax-example, + json-in-javascript-tutorial-syntax-guide, + json-in-javascript-tutorial-syntax-usage, + json-in-javascript-tutorial-syntax-example-guide, + json-in-javascript-tutorial-syntax-guide-example, + json-in-javascript-tutorial-usage-example-guide, + json-in-javascript-tutorial-usage-guide-example, + json-in-javascript-tutorial-example-usage, + json-in-javascript-tutorial-example-syntax, + json-in-javascript-tutorial-example-guide-syntax, + json-in-javascript-tutorial-example-syntax-guide, + json-in-javascript-tutorial-example-usage, + json-in-javascript-tutorial-example-usage-guide, + json-in-javascript-tutorial-guide-example-syntax, + json-in-javascript-tutorial-guide-example-usage, + json-in-javascript-tutorial-guide-example-usage-syntax, + json-in-javascript-tutorial-guide-syntax-example, + json-in-javascript-tutorial-guide-syntax-usage, + json-in-javascript-tutorial-guide-syntax-usage-example, + json-in-javascript-tutorial-guide-usage-example, + ] +description: "In this tutorial, we will learn about JSON in JavaScript. JSON stands for JavaScript Object Notation. It is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate." +--- + +JSON stands for JavaScript Object Notation. It is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. + +**JSON is built on two structures:** + +1. A collection of key/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. +2. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. + +These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures. + +**In JSON, they take on these forms:** + +1. An object is an unordered set of name/value pairs. An object begins with `{` (left brace) and ends with `}` (right brace). Each name is followed by `:` (colon) and the name/value pairs are separated by `,` (comma). +2. An array is an ordered collection of values. An array begins with `[` (left bracket) and ends with `]` (right bracket). Values are separated by `,` (comma). +3. A value can be a string in double quotes, a number, `true`, `false`, `null`, an object, or an array. These structures can be nested. +4. JSON is often used to exchange data between a server and a web application. + +In this tutorial, we will learn how to work with JSON in JavaScript. We will learn how to parse JSON data, stringify JSON data, and how to work with JSON objects and arrays in JavaScript. We will also learn how to convert JSON data to JavaScript objects and arrays and vice versa. We will also learn how to work with JSON data in JavaScript using the JSON object. We will also learn how to handle errors when working with JSON data in JavaScript. We will also learn how to work with JSON data in JavaScript using the fetch API. We will also learn how to work with JSON data in JavaScript using the XMLHttpRequest object. We will also learn how to work with JSON data in JavaScript using the jQuery library. We will also learn how to work with JSON data in JavaScript using the Axios library. + +## JSON Syntax + +JSON syntax is derived from JavaScript object notation syntax: + +1. Data is in name/value pairs. + + - Data is separated by commas. + - Curly braces hold objects. + - Square brackets hold arrays. + +
+ + ```js title="data.json" + { + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + } + ``` + +2. Data is in key/value pairs. + + - Keys must be strings. + - Values must be valid JSON data types. + - Each key/value pair is separated by a comma. + - The key is separated from the value by a colon. + +
+ + ```js title="data.json" + { + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + } + ``` + +3. JSON values can be: + + - A string. + - A number. + - An object (JSON object). + - An array. + - A boolean. + - `null`. + +## JSON Data Types + +JSON supports the following data types: + +1. **String**: A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslashes (`\`) to escape characters. + + ```js title="data.json" + { + "name": "Ajay Dhangar" + } + ``` + +2. **Number**: A number is a signed decimal number that may contain a fractional part and may use exponential `E` notation. + + ```js title="data.json" + { + "age": 23 + } + ``` + +3. **Object**: An object is an unordered collection of key/value pairs. + + ```js title="data.json" + { + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + } + ``` + +4. **Array**: An array is an ordered collection of values. + + ```js title="data.json" + { + "courses": ["Math", "Science", "English"] + } + ``` + +5. **Boolean**: A boolean is either `true` or `false`. + + ```js title="data.json" + { + "isStudent": true + } + ``` + +6. **Null**: A null value represents a `null` value. + + ```js title="data.json" + { + "address": null + } + ``` + +## JSON in JavaScript + +In JavaScript, you can work with JSON data using the following methods: + +1. **`JSON.parse()`**: The `JSON.parse()` method parses a JSON string and returns a JavaScript object. + + ```js title="JSON.parse() Example" + const jsonString = `{ + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + }`; + + const jsonObject = JSON.parse(jsonString); + + console.log(jsonObject); + ``` + +2. **`JSON.stringify()`**: The `JSON.stringify()` method converts a JavaScript object or value to a JSON string. + + ```js title="JSON.stringify() Example" + const jsonObject = { + name: "Ajay Dhangar", + age: 23, + isStudent: true, + courses: ["Math", "Science", "English"], + address: { + street: "Mandsaur, MP", + city: "Mandsaur", + state: "MP", + zip: "458002" + } + }; + + const jsonString = JSON.stringify(jsonObject); + + console.log(jsonString); // + + ``` + +3. **`JSON` Object**: The `JSON` object provides methods for working with JSON data. + + - `JSON.parse()`: Parses a JSON string and returns a JavaScript object. + - `JSON.stringify()`: Converts a JavaScript object or value to a JSON string. + +
+ + ```js title="JSON Object Example" + const jsonString = `{ + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + }`; + + const jsonObject = JSON.parse(jsonString); + + console.log(jsonObject); + + const jsonString = JSON.stringify(jsonObject); + + console.log(jsonString); + ``` + +4. **Fetch API**: The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. + + ```js title="Fetch API Example" + fetch('https://jsonplaceholder.typicode.com/posts') + .then(response => response.json()) + .then(data => console.log(data)) + .catch(error => console.error(error)); + ``` + +5. **XMLHttpRequest Object**: The `XMLHttpRequest` object is used to interact with servers. + + ```js title="XMLHttpRequest Object Example" + const xhr = new XMLHttpRequest(); + + xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true); + + xhr.onload = function () { + if (xhr.status >= 200 && xhr.status < 300) { + console.log(JSON.parse(xhr.responseText)); + } else { + console.error('Request failed with status:', xhr.status); + } + }; + + xhr.send(); + ``` + +6. **jQuery Library**: The jQuery library provides methods for working with JSON data. + + ```js title="jQuery Library Example" + $.getJSON('https://jsonplaceholder.typicode.com/posts', function(data) { + console.log(data); + }); + ``` + +7. **Axios Library**: The Axios library provides methods for working with JSON data. + + ```js title="Axios Library Example" + axios.get('https://jsonplaceholder.typicode.com/posts') + .then(response => console.log(response.data)) + .catch(error => console.error(error)); + ``` + +## JSON Error Handling + +When working with JSON data in JavaScript, you should handle errors to prevent your application from crashing. You can handle errors using the `try...catch` statement. + +```js title="Error Handling Example" +try { + const jsonString = `{ + "name": "Ajay Dhangar", + "age": 23, + "isStudent": true, + "courses": ["Math", "Science", "English"], + "address": { + "street": "Mandsaur, MP", + "city": "Mandsaur", + "state": "MP", + "zip": "458002" + } + }`; + + const jsonObject = JSON.parse(jsonString); + + console.log(jsonObject); +} catch (error) { + console.error(error); +} +``` + +In the above example, we are using the `try...catch` statement to handle errors when parsing JSON data. If an error occurs while parsing JSON data, the error will be caught and logged to the console. + +:::info Note +You should always handle errors when working with JSON data in JavaScript to prevent your application from crashing. +::: + +## Conclusion + +In this tutorial, we learned about JSON in JavaScript. We learned how to parse JSON data, stringify JSON data, and how to work with JSON objects and arrays in JavaScript. We also learned how to convert JSON data to JavaScript objects and arrays and vice versa. We also learned how to work with JSON data in JavaScript using the JSON object. We also learned how to handle errors when working with JSON data in JavaScript. We also learned how to work with JSON data in JavaScript using the fetch API. We also learned how to work with JSON data in JavaScript using the XMLHttpRequest object. We also learned how to work with JSON data in JavaScript using the jQuery library. We also learned how to work with JSON data in JavaScript using the Axios library. JSON is a powerful data interchange format that is widely used in web development. It is easy to read and write and easy to parse and generate. JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages. JSON is built on two structures: A collection of key/value pairs and an ordered list of values. JSON is often used to exchange data between a server and a web application. It is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON is a universal data structure that is supported by virtually all modern programming languages. \ No newline at end of file diff --git a/languages-platforms/javascript/let-js.md b/languages-platforms/javascript/let-js.md new file mode 100644 index 0000000..ab919ba --- /dev/null +++ b/languages-platforms/javascript/let-js.md @@ -0,0 +1,110 @@ +--- +id: let-in-javascript +title: Let Keyword in JavaScript +sidebar_label: Let Keyword +sidebar_position: 8 +tags: [JavaScript, let, ES6, Variables, Block Scope, Hoisting, Redeclaration] +description: What is the let keyword in JavaScript and how to use it. +--- + +In JavaScript, the `let` keyword is used to declare a block-scoped variable. It was introduced in ECMAScript 6 (ES6) and is the preferred way to declare variables in modern JavaScript. + +> ***ES6 (ECMAScript 2015) is a major update to JavaScript that adds new syntax and features to the language. It was officially released in June 2015.*** + +## Syntax + +The syntax to declare a variable using the `let` keyword is: + +```js title="Syntax" +let variableName = value; +``` + +Here, `variableName` is the name of the variable and `value` is the value assigned to the variable. + +## Example + +Let's see an example to understand how to use the `let` keyword in JavaScript: + +```js title="Example" +let name = "John"; +console.log(name); // Output: John +``` + +In the above example, we have declared a variable `name` using the `let` keyword and assigned it a value `"John"`. We then printed the value of the variable using `console.log()`. + +## Block Scope + +The `let` keyword is block-scoped, which means that the variable declared using `let` is only available within the block in which it is defined. + +```js title="Block Scope" +{ + let x = 10; + console.log(x); // Output: 10 +} + +console.log(x); // Uncaught ReferenceError: x is not defined +``` + +In the above example, the variable `x` is only available within the block in which it is defined. If we try to access it outside the block, it will result in a `ReferenceError`. + +## Redeclaration + +The `let` keyword does not allow redeclaration of the same variable within the same block scope. + +```js title="Redeclaration" +let x = 10; +let x = 20; // Uncaught SyntaxError: Identifier 'x' has already been declared +``` + +In the above example, we are trying to redeclare the variable `x` within the same block scope, which results in a `SyntaxError`. + +## Hoisting + +Variables declared using the `let` keyword are not hoisted to the top of their block. This means that you cannot access the variable before it is declared. + +```js title="Hoisting" +console.log(x); // Uncaught ReferenceError: x is not defined +let x = 10; +``` + +In the above example, we are trying to access the variable `x` before it is declared, which results in a `ReferenceError`. + +## Comparison with var + +The `let` keyword differs from the `var` keyword in terms of block scope, redeclaration, and hoisting. + +### Block Scope + +Variables declared using the `var` keyword are function-scoped or globally-scoped, whereas variables declared using the `let` keyword are block-scoped. + +```js title="Block Scope" +// var +function varExample() { + if (true) { + var x = 10; + } + console.log(x); // Output: 10 +} + +varExample(); + +// let +function letExample() { + if (true) { + let x = 10; + } + console.log(x); // Uncaught ReferenceError: x is not defined +} + +letExample(); +``` + +In the above example, the variable `x` declared using the `var` keyword is available outside the block in which it is defined, whereas the variable `x` declared using the `let` keyword is not available outside the block. + +:::info +A block is a set of statements enclosed in curly braces `{}`. +::: + +## Conclusion + +In this article, we learned about the `let` keyword in JavaScript and how to use it to declare block-scoped variables. We also saw how the `let` keyword differs from the `var` keyword in terms of block scope, redeclaration, and hoisting. \ No newline at end of file diff --git a/languages-platforms/javascript/maps.md b/languages-platforms/javascript/maps.md new file mode 100644 index 0000000..2342b20 --- /dev/null +++ b/languages-platforms/javascript/maps.md @@ -0,0 +1,863 @@ +--- +id: map-in-javascript +title: Maps in JavaScript +sidebar_label: Maps +sidebar_position: 27 +tags: + [ + JavaScript, + Map, + Data Structure, + Collection, + Key, + Value, + Pairs, + Iteration, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + ] +description: "In this tutorial, we will learn about maps in JavaScript. We will learn how to use maps to store key-value pairs in JavaScript." +--- + +In JavaScript, a `Map` is a built-in object that allows you to store key-value pairs. It is often used when you want to store a collection of key-value pairs and access them by their keys. + +## Creating a Map + +You can create a new `Map` by using the `new` keyword followed by the `Map` constructor. You can pass an iterable + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +console.log(map); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +- The `Map` constructor creates a new `Map` object. +- You can pass an iterable (such as an array of key-value pairs) to the `Map` constructor to initialize the map with the key-value pairs from the iterable. +- The `Map` object stores key-value pairs, so any duplicate keys will be overwritten. +- The order of elements in a `Map` is guaranteed to be the same as the order of insertion. +- The `Map` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. +- The `Map` object has a `size` property that returns the number of key-value pairs in the map. +- The `Map` object has methods to add, delete, and check for the presence of key-value pairs. +- The `Map` object does not have methods to access key-value pairs by index, as it does not maintain the order of elements. +- The `Map` object can store any type of key or value, including objects, functions, and other maps. +- The `Map` object can store key-value pairs with the same key, as it uses the `===` operator to compare keys. +- The `Map` object can store key-value pairs with `NaN` as the key, as it uses the `===` operator to compare keys. + +## Adding Key-Value Pairs to a Map + +You can add key-value pairs to a `Map` by using the `set` method. + +```js title="app.js" +const map = new Map(); +map.set("name", "John"); +map.set("age", 23); +map.set("person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}); +console.log(map); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +In this example, the `set` method is used to add key-value pairs to the map. The first argument to the `set` method is the key, and the second argument is the value. + +- The `set` method is used to add a new key-value pair to the map. +- If the key is already present in the map, its value will be updated with the new value. +- The `set` method returns the `Map` object, so you can chain multiple `set` calls together. +- The `set` method can store any type of key or value, including objects, functions, and other maps. +- The `set` method can store key-value pairs with the same key, as it uses the `===` operator to compare keys. +- The `set` method can store key-value pairs with `NaN` / `undefined` as the key, as it uses the `===` operator to compare keys. + +## Deleting Key-Value Pairs from a Map + +You can delete key-value pairs from a `Map` by using the `delete` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +map.delete("age"); + +console.log(map); // Map { 'name' => 'John', 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +In this example, the `delete` method is used to remove the key-value pair with the key `"age"` from the map. The `delete` method returns `true` if the key-value pair is removed, and `false` otherwise. + +- The `delete` method is used to remove a key-value pair from the map. +- If the key is present in the map, the key-value pair will be removed, and the method will return `true`. +- If the key is not present in the map, the method will return `false`. +- The `delete` method does not throw an error if the key is not present in the map. +- The `delete` method does not return the removed key-value pair. +- The `delete` method is chainable, so you can remove multiple key-value pairs from the map in a single statement. +- The `delete` method can be used to remove key-value pairs with `NaN` / `undefined` as the key, as it uses the `===` operator to compare keys. +- The `delete` method can be used to remove key-value pairs with the same key, as it uses the `===` operator to compare keys. + +## Checking for the Presence of a Key in a Map + +You can check if a key is present in a `Map` by using the `has` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +console.log(map.has("age")); // true +``` + +In this example, the `has` method is used to check if the key `"age"` is present in the map. If the key is present, the method will return `true`; otherwise, it will return `false`. + +- The `has` method is used to check if a key is present in the map. +- If the key is present in the map, the method will return `true`. +- If the key is not present in the map, the method will return `false`. +- The `has` method does not throw an error if the key is not present in the map. +- The `has` method does not return the key itself. +- The `has` method is often used to check if a key is present in the map before adding or deleting it. +- The `has` method can be used to check for the presence of `NaN` / `undefined` as the key, as it uses the `===` operator to compare keys. +- The `has` method can be used to check for the presence of the same key, as it uses the `===` operator to compare keys. +- The `has` method can be used to check for the presence of a key with a value of `undefined`. + +## Iterating Over a Map + +You can iterate over the key-value pairs of a `Map` by using a `for...of` loop. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const [key, value] of map) { + console.log(key + ": " + value); +} +``` + +The `for...of` loop is used to iterate over the key-value pairs of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `[key, value]`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Iterating Over the Keys of a Map + +You can iterate over the keys of a `Map` by using the `keys` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key of map.keys()) { + console.log(key); +} +``` + +The `keys` method is used to iterate over the keys of the map. In each iteration, the value of the current key is assigned to the loop variable `key`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key of the current key-value pair is printed to the console. + +## Iterating Over the Values of a Map + +You can iterate over the values of a `Map` by using the `values` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const value of map.values()) { + console.log(value); +} +``` + +The `values` method is used to iterate over the values of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `value`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +John +23 +[object Object] +``` + +In each iteration, the value of the current key-value pair is printed to the console. + +## Converting a Map to an Array + +You can convert a `Map` to an array by using the `Array.from` method or the spread operator (`...`). + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const array = Array.from(map); + +console.log(array); // [ [ 'name', 'John' ], [ 'age', 23 ], [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] ] +``` + +- The `Array.from` method is used to create a new array from an iterable (such as a `Map`). +- The `Array.from` method returns a new array that contains the key-value pairs of the map. +- The spread operator (`...`) can also be used to create a new array from an iterable. +- The spread operator (`...`) returns a new array that contains the key-value pairs of the map. +- The `Array.from` method and the spread operator (`...`) can be used to convert a `Map` to an array of key-value pairs. +- The `Array.from` method and the spread operator (`...`) can be used to convert a `Map` to an array of keys or values. + +## Using the Map Constructor + +You can use the `Map` constructor to create an empty `Map` and then add key-value pairs to it. + +```js title="app.js" +const map = new Map(); +map.set("name", "John"); +map.set("age", 23); +map.set("person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, +}); + +console.log(map); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +The `Map` constructor creates a new empty `Map` object. You can then use the `set` method to add key-value pairs to the map. The `Map` object stores key-value pairs, so any duplicate keys will be overwritten. + +## Using the Spread Operator + +You can use the spread operator (`...`) to create a new `Map` from an existing `Map`. + +```js title="app.js" +const map1 = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const map2 = new Map([...map1]); + +console.log(map2); // Map { 'name' => 'John', 'age' => 23, 'person' => { name: 'John', age: 23, greet: [Function: greet] } } +``` + +The spread operator (`...`) is used to create a new `Map` from an existing `Map`. The new `Map` contains the key-value pairs of the existing `Map`. + +## Using the `forEach` Method + +You can use the `forEach` method to iterate over the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +map.forEach((value, key) => { + console.log(key + ": " + value); +}); +``` + +The `forEach` method is used to iterate over the key-value pairs of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `value`, and the key is assigned to the loop variable `key`. The loop body is executed for each key-value pair. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Using the `clear` Method + +You can use the `clear` method to remove all key-value pairs from a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +map.clear(); + +console.log(map); // Map {} +``` + +The `clear` method is used to remove all key-value pairs from the map. After calling the `clear` method, the map will be empty. + +The `clear` method does not return any value. + +The `clear` method can be used to remove all key-value pairs from the map in a single statement. + +## Using the `size` Property + +You can use the `size` property to get the number of key-value pairs in a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +console.log(map.size); // 3 +``` + +The `size` property returns the number of key-value pairs in the map. It can be used to get the size of the map in a single statement. + +The `size` property is read-only, so you cannot change its value. + +The `size` property can be used to get the number of key-value pairs in the map. + +## Using the `entries` Method + +You can use the `entries` method to get an iterator that contains the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map.entries(); + +console.log(iterator.next().value); // [ 'name', 'John' ] +console.log(iterator.next().value); // [ 'age', 23 ] +console.log(iterator.next().value); // [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] +``` + +The `entries` method returns an iterator that contains the key-value pairs of the map. You can use the `next` method of the iterator to get the next key-value pair. + +The `entries` method can be used to get an iterator that contains the key-value pairs of the map. + +The `entries` method can be used to iterate over the key-value pairs of the map. + +## Using the `keys` Method + +You can use the `keys` method to get an iterator that contains the keys of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map.keys(); + +console.log(iterator.next().value); // name +console.log(iterator.next().value); // age +console.log(iterator.next().value); // person +``` + +The `keys` method returns an iterator that contains the keys of the map. You can use the `next` method of the iterator to get the next key. + +The `keys` method can be used to get an iterator that contains the keys of the map. + +The `keys` method can be used to iterate over the keys of the map. + +## Using the `values` Method + +You can use the `values` method to get an iterator that contains the values of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map.values(); + +console.log(iterator.next().value); // John +console.log(iterator.next().value); // 23 +console.log(iterator.next().value); // { name: 'John', age: 23, greet: [Function: greet] } +``` + +The `values` method returns an iterator that contains the values of the map. You can use the `next` method of the iterator to get the next value. + +The `values` method can be used to get an iterator that contains the values of the map. + +The `values` method can be used to iterate over the values of the map. + +## Using the `Symbol.iterator` Property + +You can use the `Symbol.iterator` property to get an iterator that contains the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const iterator = map[Symbol.iterator](); + +console.log(iterator.next().value); // [ 'name', 'John' ] +console.log(iterator.next().value); // [ 'age', 23 ] +console.log(iterator.next().value); // [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] +``` + +The `Symbol.iterator` property returns an iterator that contains the key-value pairs of the map. You can use the `next` method of the iterator to get the next key-value pair. + +The `Symbol.iterator` property can be used to get an iterator that contains the key-value pairs of the map. + +The `Symbol.iterator` property can be used to iterate over the key-value pairs of the map. + +## Using the `for...of` Loop + +You can use a `for...of` loop to iterate over the key-value pairs of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const [key, value] of map) { + console.log(key + ": " + value); +} +``` + +The `for...of` loop is used to iterate over the key-value pairs of the map. In each iteration, the value of the current key-value pair is assigned to the loop variable `[key, value]`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Using the `for...of` Loop with the `entries` Method + +You can use a `for...of` loop to iterate over the key-value pairs of a `Map` by using the `entries` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const [key, value] of map.entries()) { + console.log(key + ": " + value); +} +``` + +The `for...of` loop is used to iterate over the key-value pairs of the map by using the `entries` method. In each iteration, the value of the current key-value pair is assigned to the loop variable `[key, value]`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name: John +age: 23 +person: [object Object] +``` + +In each iteration, the key and value of the current key-value pair are printed to the console. + +## Using the `for...of` Loop with the `keys` Method + +You can use a `for...of` loop to iterate over the keys of a `Map` by using the `keys` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key of map.keys()) { + console.log(key); +} +``` + +The `for...of` loop is used to iterate over the keys of the map by using the `keys` method. In each iteration, the value of the current key is assigned to the loop variable `key`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key of the current key-value pair is printed to the console. + +## Using the `for...of` Loop with the `values` Method + +You can use a `for...of` loop to iterate over the values of a `Map` by using the `values` method. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const value of map.values()) { + console.log(value); +} +``` + +The `for...of` loop is used to iterate over the values of the map by using the `values` method. In each iteration, the value of the current key-value pair is assigned to the loop variable `value`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +John +23 +[object Object] +``` + +In each iteration, the value of the current key-value pair is printed to the console. + +## Using the `for...in` Loop + +You can use a `for...in` loop to iterate over the keys of a `Map`. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key in map) { + console.log(key); +} +``` + +The `for...in` loop is used to iterate over the keys of the map. In each iteration, the value of the current key is assigned to the loop variable `key`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key of the current key-value pair is printed to the console. + +## Using the `hasOwnProperty` Method + +To check if the key is a direct property of the map and not inherited from its prototype chain, you can use the `hasOwnProperty` method. Here's an example: + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +for (const key in map) { + if (map.hasOwnProperty(key)) { + console.log(key); + } +} +``` + +In this example, the `hasOwnProperty` method is used to check if the key is a direct property of the map. If it is, the key is printed to the console. + +The output of the above example will be: + +```plaintext title="Output" +name +age +person +``` + +In each iteration, the key is checked if it is a direct property of the map. If it is, the key is printed to the console. + +## Using the `Array.from` Method + +You can use the `Array.from` method to convert a `Map` to an array of key-value pairs. + +```js title="app.js" +const map = new Map([ + ["name", "John"], + ["age", 23], + ["person", { + name: "John", + age: 23, + greet: function () { + console.log( + "Hello, I am " + this.name + " and I am " + this.age + " years old." + ); + }, + }], +]); + +const array = Array.from(map); + +console.log(array); // [ [ 'name', 'John' ], [ 'age', 23 ], [ 'person', { name: 'John', age: 23, greet: [Function: greet] } ] ] +``` + +The `Array.from` method is used to create a new array from the map. The new array contains the key-value pairs of the map. + +The `Array.from` method can be used to convert a `Map` to an array of key-value pairs. + +The `Array.from` method can be used to convert a `Map` to an array of keys or values. + +:::info ๐Ÿ“ Note + +## Why Use Maps? + +Maps are often used when you want to store a collection of key-value pairs and access them by their keys. They are more flexible than objects, as they can store any type of key or value, including objects, functions, and other maps. They can also store key-value pairs with the same key, as they use the `===` operator to compare keys. + +## Benefits of Using Maps + +- Maps are iterable, so you can use them in a `for...of` loop to iterate over their elements. +- Maps have a `size` property that returns the number of key-value pairs in the map. +- Maps have methods to add, delete, and check for the presence of key-value pairs. +- Maps do not have methods to access key-value pairs by index, as they do not maintain the order of elements. +- Maps can store any type of key or value, including objects, functions, and other maps. +- Maps can store key-value pairs with the same key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `NaN` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `undefined` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `null` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `0` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with `false` as the key, as they use the `===` operator to compare keys. +- Maps can store key-value pairs with an empty string as the key, as they use the `===` operator to compare keys. + +## When to Use Maps + +- Use maps when you want to store a collection of key-value pairs and access them by their keys. +- Use maps when you want to store key-value pairs with the same key, as maps can store duplicate keys. +- Use maps when you want to store key-value pairs with `NaN` as the key, as maps can store `NaN` as the key. +- Use maps when you want to store key-value pairs with `undefined` as the key, as maps can store `undefined` as the key. +- Use maps when you want to store key-value pairs with `null` as the key, as maps can store `null` as the key. +- Use maps when you want to store key-value pairs with `0` as the key, as maps can store `0` as the key. +- Use maps when you want to store key-value pairs with `false` as the key, as maps can store `false` as the key. + +## When Not to Use Maps + +- Do not use maps when you want to access key-value pairs by index, as maps do not maintain the order of elements. +- Do not use maps when you want to store key-value pairs with the same key, as maps will overwrite the existing key-value pair. +- Do not use maps when you want to store key-value pairs with `NaN` as the key, as maps will treat `NaN` as the same key. +- Do not use maps when you want to store key-value pairs with `undefined` as the key, as maps will treat `undefined` as the same key. +- Do not use maps when you want to store key-value pairs with `null` as the key, as maps will treat `null` as the same key. +- Do not use maps when you want to store key-value pairs with `0` as the key, as maps will treat `0` as the same key. +- Do not use maps when you want to store key-value pairs with `false` as the key, as maps will treat `false` as the same key. + +::: + +## Summary + +In this tutorial, we learned about maps in JavaScript. We learned how to use maps to store key-value pairs in JavaScript. We also learned how to add, delete, and check for the presence of key-value pairs in a map. Finally, we learned how to iterate over the key-value pairs, keys, and values of a map. \ No newline at end of file diff --git a/languages-platforms/javascript/math.md b/languages-platforms/javascript/math.md new file mode 100644 index 0000000..2ac8cc6 --- /dev/null +++ b/languages-platforms/javascript/math.md @@ -0,0 +1,261 @@ +--- +id: math-in-javascript +title: Math in JavaScript +sidebar_label: Math +sidebar_position: 17 +tags: [JavaScript, Math, Object, Properties, Methods] +description: "In this tutorial, we will learn about the Math object in JavaScript. We will learn about the properties and methods of the Math object." +--- + +In JavaScript, the `Math` object is a built-in object that has properties and methods for mathematical constants and functions. It allows you to perform mathematical tasks on numbers. + +## Properties + +The `Math` object has the following properties: + +- `Math.E`: Returns Euler's number, the base of natural logarithms, approximately 2.718. + + for example: + + ```js title="app.js" + console.log(Math.E); // 2.718281828459045 + ``` + +- `Math.PI`: Returns the ratio of the circumference of a circle to its diameter, approximately 3.14159. + for example: + + ```js title="app.js" + console.log(Math.PI); // 3.141592653589793 + ``` + +- `Math.LN2`: Returns the natural logarithm of 2, approximately 0.693. + for example: + + ```js title="app.js" + console.log(Math.LN2); // 0.6931471805599453 + ``` + +- `Math.LN10`: Returns the natural logarithm of 10, approximately 2.303. + for example: + + ```js title="app.js" + console.log(Math.LN10); // 2.302585092994046 + ``` + +- `Math.LOG2E`: Returns the base 2 logarithm of E, approximately 1.442. + + for example: + + ```js title="app.js" + console.log(Math.LOG2E); // 1.4426950408889634 + ``` + +- `Math.LOG10E`: Returns the base 10 logarithm of E, approximately 0.434. + + for example: + + ```js title="app.js" + console.log(Math.LOG10E); // 0.4342944819032518 + ``` + +- `Math.SQRT1_2`: Returns the square root of 1/2, approximately 0.707. + + for example: + + ```js title="app.js" + console.log(Math.SQRT1_2); // 0.7071067811865476 + ``` + +- `Math.SQRT2`: Returns the square root of 2, approximately 1.414. + + for example: + + ```js title="app.js" + console.log(Math.SQRT2); // 1.4142135623730951 + ``` + +## Methods + +The `Math` object has the following methods: + +- `Math.abs(x)`: Returns the absolute value of a number. + + for example: + + ```js title="app.js" + console.log(Math.abs(-5)); // 5 + console.log(Math.abs(5)); // 5 + ``` + +- `Math.ceil(x)`: Returns the smallest integer greater than or equal to a number. + + for example: + + ```js title="app.js" + console.log(Math.ceil(5.1)); // 6 + console.log(Math.ceil(5.9)); // 6 + ``` + +- `Math.floor(x)`: Returns the largest integer less than or equal to a number. + + for example: + + ```js title="app.js" + console.log(Math.floor(5.1)); // 5 + console.log(Math.floor(5.9)); // 5 + ``` + +- `Math.round(x)`: Returns the value of a number rounded to the nearest integer. + + for example: + + ```js title="app.js" + console.log(Math.round(5.1)); // 5 + console.log(Math.round(5.9)); // 6 + ``` + +- `Math.max(x, y, z, ..., n)`: Returns the largest of zero or more numbers. + + for example: + + ```js title="app.js" + console.log(Math.max(5, 10, 15, 20)); // 20 + ``` + +- `Math.min(x, y, z, ..., n)`: Returns the smallest of zero or more numbers. + + for example: + + ```js title="app.js" + console.log(Math.min(5, 10, 15, 20)); // 5 + ``` + +- `Math.pow(x, y)`: Returns the value of x to the power of y. + + for example: + + ```js title="app.js" + console.log(Math.pow(2, 3)); // 8 + ``` + +- `Math.sqrt(x)`: Returns the square root of a number. + + for example: + + ```js title="app.js" + console.log(Math.sqrt(16)); // 4 + ``` + +- `Math.random()`: Returns a random number between 0 (inclusive), and 1 (exclusive). + + for example: + + ```js title="app.js" + console.log(Math.random()); // 0.123456789 + ``` + +- `Math.sin(x)`: Returns the sine of a number. + + for example: + + ```js title="app.js" + console.log(Math.sin(90)); // 0.8939966636005579 + ``` + +- `Math.cos(x)`: Returns the cosine of a number. + + for example: + + ```js title="app.js" + console.log(Math.cos(0)); // 1 + ``` + +- `Math.tan(x)`: Returns the tangent of a number. + + for example: + + ```js title="app.js" + console.log(Math.tan(45)); // 1.6197751905438615 + ``` + +- `Math.log(x)`: Returns the natural logarithm (base E) of a number. + + for example: + + ```js title="app.js" + console.log(Math.log(2)); // 0.6931471805599453 + ``` + +- `Math.exp(x)`: Returns the value of E^x. + + for example: + + ```js title="app.js" + console.log(Math.exp(2)); // 7.3890560989306495 + ``` + +- `Math.atan(x)`: Returns the arctangent of a number. + + for example: + + ```js title="app.js" + console.log(Math.atan(1)); // 0.7853981633974483 + ``` + +- `Math.acos(x)`: Returns the arccosine of a number. + + for example: + + ```js title="app.js" + console.log(Math.acos(0)); // 1.5707963267948966 + ``` + +- `Math.asin(x)`: Returns the arcsine of a number. + + for example: + + ```js title="app.js" + console.log(Math.asin(1)); // 1.5707963267948966 + ``` + +- `Math.atan2(y, x)`: Returns the arctangent of the quotient of its arguments. + + for example: + + ```js title="app.js" + console.log(Math.atan2(1, 1)); // 0.7853981633974483 + ``` + +- `Math.cosh(x)`: Returns the hyperbolic cosine of a number. + + for example: + + ```js title="app.js" + console.log(Math.cosh(0)); // 1 + ``` + +- `Math.sinh(x)`: Returns the hyperbolic sine of a number. + + for example: + + ```js title="app.js" + console.log(Math.sinh(0)); // 0 + ``` + +- `Math.tanh(x)`: Returns the hyperbolic tangent of a number. + + for example: + + ```js title="app.js" + console.log(Math.tanh(0)); // 0 + ``` + +:::tip ๐Ÿ“ Note + +The `Math` object is not a constructor. All properties and methods of the `Math` object can be called by using the `Math` object as a namespace. + +::: + +## Conclusion + +In this tutorial, we learned about the `Math` object in JavaScript. We learned about the properties and methods of the `Math` object. We also saw examples of how to use the `Math` object to perform mathematical tasks on numbers. \ No newline at end of file diff --git a/languages-platforms/javascript/mistakes-js.md b/languages-platforms/javascript/mistakes-js.md new file mode 100644 index 0000000..23ff567 --- /dev/null +++ b/languages-platforms/javascript/mistakes-js.md @@ -0,0 +1,207 @@ +--- +id: mistakes-in-js +title: Mistakes in JavaScript +sidebar_label: Mistakes +sidebar_position: 42 +tags: [ JavaScript, Mistakes, Common Mistakes in JavaScript, JavaScript Mistakes, JavaScript Mistakes Tutorial, JavaScript Mistakes Example, JavaScript Mistakes to Avoid, JavaScript Common Mistakes, JavaScript Common Mistakes Tutorial, JavaScript Common Mistakes Example ] +description: "In this tutorial, we will learn about the common mistakes in JavaScript that developers make and how to avoid them. We will learn about the common pitfalls, bugs, and errors in JavaScript code and how to fix them." +--- + +JavaScript is a powerful and flexible language, but it is also easy to make mistakes while writing code. In this tutorial, we will learn about the common mistakes in JavaScript that developers make and how to avoid them. By understanding these mistakes and pitfalls, you can write better and more reliable JavaScript code. + +## Common Mistakes in JavaScript + +### Misunderstanding Variable Scope + +One common mistake in JavaScript is misunderstanding variable scope. JavaScript has function-level scope, which means that variables declared inside a function are only accessible within that function. If you declare a variable without the `var`, `let`, or `const` keyword, it becomes a global variable and is accessible throughout the entire script. This can lead to unintended side effects and bugs in your code. + + + + + ```javascript + function myFunction() { + let localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + + + ```javascript + function myFunction() { + localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + + +### Using `==` Instead of `===` + +Another common mistake in JavaScript is using the `==` operator instead of the `===` operator. The `==` operator performs type coercion, which means that it converts the operands to the same type before comparing them. This can lead to unexpected results and bugs in your code. The `===` operator, on the other hand, performs strict equality comparison, which means that it compares the operands without type coercion. + + + + + ```javascript + let x = 10; + let y = "10"; + + if (x === 10) { + console.log("x is equal to 10"); + } + + if (x === y) { + console.log("x is equal to y"); + } + ``` + + + + + ```javascript + let x = 10; + let y = "10"; + + if (x == 10) { + console.log("x is equal to 10"); + } + + if (x == y) { + console.log("x is equal to y"); + } + ``` + + + + +### Ignoring Asynchronous Code + +JavaScript is a single-threaded language, which means that it can only execute one piece of code at a time. Asynchronous code allows you to perform time-consuming tasks without blocking the main thread. One common mistake in JavaScript is ignoring asynchronous code and performing time-consuming tasks synchronously. This can lead to slow performance and unresponsive user interfaces. + + + + + ```javascript + function fetchData() { + fetch("https://api.github.com/users") + .then(response => response.json()) + .then(data => console.log(data)) + .catch(error => console.error(error)); + } + + fetchData(); // Fetch and log data asynchronously + ``` + + + + + ```javascript + function fetchData() { + let response = fetch("https://api.github.com/users"); + let data = response.json(); + console.log(data); + } + + fetchData(); // Fetch and log data synchronously + ``` + + + + +### Not Handling Errors + +Another common mistake in JavaScript is not handling errors properly. Errors can occur at any time in your code, and if they are not handled correctly, they can crash your application. It is important to use try-catch blocks or promise.catch() to catch and handle errors in your code. + + + + + ```javascript + async function fetchData() { + try { + let response = await fetch("https://api.github.com/users"); + let data = await response.json(); + console.log(data); + } catch (error) { + console.error("Error fetching data:", error); + } + } + + fetchData(); // Fetch and log data with error handling + + ``` + + + + + ```javascript + async function fetchData() { + let response = await fetch("https://api.github.com/users"); + let data = await response.json(); + console.log(data); + } + + fetchData(); // Fetch and log data without error handling + ``` + + + + +### Not Using Strict Mode + +Strict mode is a feature in JavaScript that helps you write cleaner and more secure code. It catches common coding mistakes and prevents certain actions that are considered bad practice. One common mistake in JavaScript is not using strict mode in your code. + + + + + ```javascript + "use strict"; + + // Code that follows strict mode + ``` + + + + + ```javascript + // Code that does not follow strict mode + ``` + + + + +### Not Using `let` and `const` + +Another common mistake in JavaScript is not using the `let` and `const` keywords to declare variables. The `let` keyword is used to declare block-scoped variables, while the `const` keyword is used to declare constants. Using `let` and `const` helps prevent unintended side effects and bugs in your code. + + + + + ```javascript + let x = 10; + const y = 20; + ``` + + + + + ```javascript + var x = 10; + y = 20; + + console.log(x); // 10 + console.log(y); // 20 + ``` + + + + +## Conclusion + +In this tutorial, we learned about the common mistakes in JavaScript that developers make and how to avoid them. By understanding these mistakes and pitfalls, you can write better and more reliable JavaScript code. We covered common mistakes such as misunderstanding variable scope, using `==` instead of `===`, ignoring asynchronous code, not handling errors, not using strict mode, and not using `let` and `const`. By avoiding these mistakes, you can write cleaner, more secure, and more efficient JavaScript code. \ No newline at end of file diff --git a/languages-platforms/javascript/modules-js.md b/languages-platforms/javascript/modules-js.md new file mode 100644 index 0000000..b751b22 --- /dev/null +++ b/languages-platforms/javascript/modules-js.md @@ -0,0 +1,405 @@ +--- +id: modules-in-js +title: Modules in JavaScript +sidebar_label: Modules +sidebar_position: 37 +tags: + [ + JavaScript, + Modules, + ES6, + ES2015, + ES6 Features, + ES2015 Features, + ES6 Tutorials, + ES2015 Tutorials, + ES6 Tutorial, + ES2015 Tutorial, + ES6 Modules, + ES2015 Modules, + Modules in JavaScript, + Modules in ES6, + Modules in ES2015, + JavaScript Modules, + ES6 Modules Tutorial, + ES2015 Modules Tutorial, + Modules Tutorial, + Modules in JavaScript Tutorial, + Modules in ES6 Tutorial, + Modules in ES2015 Tutorial, + JavaScript Modules Tutorial, + ES6 Modules Example, + ES2015 Modules Example, + Modules Example, + Modules in JavaScript Example, + Modules in ES6 Example, + Modules in ES2015 Example, + JavaScript Modules Example, + ES6 Modules Syntax, + ES2015 Modules Syntax, + Modules Syntax, + Modules in JavaScript Syntax, + Modules in ES6 Syntax, + Modules in ES2015 Syntax, + JavaScript Modules Syntax, + ES6 Modules Syntax Example, + ES2015 Modules Syntax Example, + Modules Syntax Example, + Modules in JavaScript Syntax Example, + Modules in ES6 Syntax Example, + Modules in ES2015 Syntax Example, + JavaScript Modules Syntax Example, + ES6 Modules Syntax Tutorial, + ES2015 Modules Syntax Tutorial, + Modules Syntax Tutorial, + Modules in JavaScript Syntax Tutorial, + Modules in ES6 Syntax Tutorial, + Modules in ES2015 Syntax Tutorial, + JavaScript Modules Syntax Tutorial, + ES6 Modules Syntax Example Tutorial, + ES2015 Modules Syntax Example Tutorial, + Modules Syntax Example Tutorial, + Modules in JavaScript Syntax Example Tutorial, + Modules in ES6 Syntax Example Tutorial, + Modules in ES2015 Syntax Example Tutorial, + JavaScript Modules Syntax Example Tutorial, + ] +description: "In this tutorial, you will learn about modules in JavaScript, a new feature introduced in ES6 (ES2015) that allows you to organize your code into reusable pieces." +--- + +In JavaScript, modules are a new feature introduced in ES6 (ES2015) that allows you to organize your code into reusable pieces. Modules are a way to split your code into separate files and import/export the parts you need. + +In this tutorial, you will learn about modules in JavaScript with the help of examples. + +## Modules in JavaScript + +The syntax for importing and exporting modules in JavaScript is as follows: + + + + + ```js + // Exporting a variable + export const PI = 3.14159; + ``` + + + + + ```js + // Exporting a function + export function add(a, b) { + return a + b; + } + ``` + + + + + ```js + // Exporting a class + export class Person { + constructor(name, age) { + this.name = name; + this.age = age; + } + + greet() { + return `Hello, my name is ${this.name} and I am ${this.age} years old.`; + } + } + ``` + + + + +```js +// Importing a variable +import { PI } from "./module1.js"; + +// Importing a function +import { add } from "./module2.js"; + +// Importing a class +import { Person } from "./module3.js"; + +console.log(PI); // Output: 3.14159 + +console.log(add(5, 3)); // Output: 8 + +const john = new Person("John", 30); + +console.log(john.greet()); // Output: Hello, my name is John and I am 30 years old. +``` + + + + + +In the example above, we have three modules: `module1.js`, `module2.js`, and `module3.js`, each exporting a variable, a function, and a class, respectively. The `app.js` file imports these modules and uses the exported values. + +Here's a breakdown of the example: + +1. `module1.js` exports a variable `PI` with the value `3.14159`. +2. `module2.js` exports a function `add` that takes two parameters and returns their sum. +3. `module3.js` exports a class `Person` with a constructor that initializes the `name` and `age` properties and a `greet` method that returns a greeting message. +4. `app.js` imports the exported values from the modules and uses them in the code. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +8 +Hello, my name is John and I am 30 years old. +``` + +This is how you can use modules in JavaScript to organize your code into reusable pieces. + +## Default Exports + +In addition to named exports, you can also use default exports in JavaScript modules. A default export is a single value that is exported from a module and can be imported without using curly braces `{}`. + +Here's an example of using default exports in JavaScript modules: + + + + +```js +// Default export +const PI = 3.14159; + +export default PI; +``` + + + + + +```js +// Default export +export default function add(a, b) { + return a + b; +} +``` + + + + + +```js +// Importing a default export +import PI from "./module1.js"; + +// Importing a default export +import add from "./module2.js"; + +console.log(PI); // Output: 3.14159 + +console.log(add(5, 3)); // Output: 8 +``` + + + + + +In this example, we have two modules: `module1.js` and `module2.js`, each exporting a single value using default exports. The `app.js` file imports these default exports without using curly braces `{}`. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +8 +``` + +This is how you can use default exports in JavaScript modules. + +## Multiple Exports and Imports in a Single Statement + +You can also export and import multiple values in a single statement using the `export` and `import` keywords. + +Here's an example of exporting and importing multiple values in a single statement: + + + + + +```js +// Exporting multiple values +export const PI = 3.14159; +export const E = 2.71828; +``` + + + + + +```js +// Exporting multiple values +export function add(a, b) { + return a + b; +} + +export function subtract(a, b) { + return a - b; +} +``` + + + + + +```js +// Importing multiple values +import { PI, E } from "./module1.js"; + +// Importing multiple values +import { add, subtract } from "./module2.js"; + +console.log(PI); // Output: 3.14159 +console.log(E); // Output: 2.71828 + +console.log(add(5, 3)); // Output: 8 + +console.log(subtract(5, 3)); // Output: 2 +``` + + + + + + +In this example, we have two modules: `module1.js` and `module2.js`, each exporting multiple values using the `export` keyword. The `app.js` file imports these multiple values in a single statement using the `import` keyword. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +2.71828 +8 +2 +``` + +This is how you can export and import multiple values in a single statement in JavaScript modules. + +:::info ๐Ÿ“ Note + +You can also use the `export * from 'module'` syntax to re-export all named exports from another module. This can be useful when you want to aggregate exports from multiple modules into a single module. + +For example: + + + + + +```js +// Exporting a variable +export const PI = 3.14159; +``` + + + + + +```js +// Exporting a variable +export const E = 2.71828; +``` + + + + + +```js +// Re-exporting named exports +export * from "./module1.js"; +export * from "./module2.js"; +``` + + + + + +```js +// Importing re-exported values +import { PI, E } from "./module.js"; + +console.log(PI); // Output: 3.14159 +console.log(E); // Output: 2.71828 +``` + + + + +In this example, we have two modules `module1.js` and `module2.js`, each exporting a variable. The `module.js` file re-exports the named exports from `module1.js` and `module2.js`. The `app.js` file imports the re-exported values from `module.js`. + +When you run `app.js`, you will see the following output: + +```bash title="Output" +3.14159 +2.71828 +``` + +This is how you can re-export named exports from other modules in JavaScript. + +::: + +:::important + +When using modules in JavaScript, you need to be aware of the module system you are using. Common module systems include CommonJS, AMD, and ES6 modules. ES6 modules are the standard module system in modern JavaScript applications. + +If you are using a module in html file, you can use the `type="module"` attribute in the ` + + + + + +``` + +In this example, the `type="module"` attribute in the ` + + + ``` + + ```javascript title="script.js" + const container = document.getElementById("container"); + const fragment = document.createDocumentFragment(); + + for (let i = 0; i < 1000; i++) { + const div = document.createElement("div"); + div.textContent = `Element ${i}`; + fragment.appendChild(div); + } + + container.appendChild(fragment); + ``` + + + + ```html title="index.html" + + + + + + + Document + + +
+ + + + ``` + + ```javascript title="script.js" + const container = document.getElementById("container"); + + for (let i = 0; i < 1000; i++) { + const div = document.createElement("div"); + div.textContent = `Element ${i}`; + container.appendChild(div); + } + ``` +
+ + +### Avoid Memory Leaks + +Memory leaks can occur in JavaScript when objects are no longer needed but are still referenced, preventing them from being garbage collected. This can lead to increased memory usage and degraded performance over time. To avoid memory leaks, you should be mindful of object references and ensure that objects are properly cleaned up when they are no longer needed. + + + + + ```javascript + function createHeavyObject() { + const obj = { + /* heavy data */ + data: Array.from({ length: 1000000 }, () => Math.random()) + }; + return obj; + } + + let obj = createHeavyObject(); + + console.log(obj.data.length); // Use obj... + + obj = null; // Clean up obj + ``` + + + + ```javascript + function createHeavyObject() { + const obj = { + /* heavy data */ + data: Array.from({ length: 1000000 }, () => Math.random()) + }; + return obj; + } + + let obj = createHeavyObject(); + + console.log(obj.data.length); // Use obj... + ``` + + + +### Optimize Loops + +Loops are a common source of performance issues in JavaScript. Inefficient loops can slow down your code, especially when dealing with large datasets. To optimize loops, you should minimize the number of iterations, avoid unnecessary work inside the loop, and use appropriate loop constructs for the task at hand. + + + + + ```javascript + const data = [1, 2, 3, 4, 5]; + + for (let i = 0; i < data.length; i++) { + console.log(data[i]); + } + ``` + + + + ```javascript + const data = [1, 2, 3, 4, 5]; + + data.forEach(item => { + console.log(item); + }); + ``` + + + +### Use Event Delegation + +Event delegation is a technique in JavaScript that allows you to attach a single event listener to a parent element, rather than multiple event listeners to individual child elements. This can improve performance by reducing the number of event listeners and simplifying event handling. + + + + + ```html title="index.html" + + + + + + + Document + + +
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
+ + + + ``` + + ```javascript title="script.js" + const list = document.getElementById("list"); + + list.addEventListener("click", function(event) { + if (event.target.tagName === "LI") { + console.log(event.target.textContent); + } + }); + ``` +
+ + + ```html title="index.html" + + + + + + + Document + + +
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
+ + + + ``` + + ```javascript title="script.js" + const items = document.querySelectorAll("li"); + + items.forEach(item => { + item.addEventListener("click", function() { + console.log(item.textContent); + }); + }); + ``` +
+
+ +### Use Efficient Data Structures + +Choosing the right data structure can have a significant impact on the performance of your JavaScript code. For example, using an object for key-value pairs can be more efficient than an array for lookups, especially for large datasets. By selecting the appropriate data structure for your needs, you can optimize the performance of your code. + + + + + ```javascript + const data = { + key1: "value1", + key2: "value2", + key3: "value3" + }; + + console.log(data.key1); + ``` + + + + ```javascript + const data = ["value1", "value2", "value3"]; + + console.log(data[0]); + ``` + + + +### Avoid Global Variables + +Global variables can lead to performance issues in JavaScript, as they are accessible from anywhere in your code and can be modified by any part of your application. This can make it difficult to track changes and optimize performance. To avoid global variables, you should encapsulate your code in modules and use local variables whenever possible. + + + + + ```javascript + function myFunction() { + const localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + + ```javascript + function myFunction() { + localVar = 10; + console.log(localVar); + } + + myFunction(); // 10 + ``` + + + +### Use `===` Instead of `==` + +Another common mistake in JavaScript is using the `==` operator instead of the `===` operator. The `==` operator performs type coercion, which means that it converts the operands to the same type before comparing them. This can lead to unexpected results and bugs in your code. The `===` operator, on the other hand, performs strict equality comparison, which means that it compares the operands without type coercion. + + + + + ```javascript + let x = 10; + let y = "10"; + + if (x === 10) { + console.log("x is equal to 10"); + } + + if (x === y) { + console.log("x is equal to y"); + } + ``` + + + + ```javascript + let x = 10; + let y = "10"; + + if (x == 10) { + console.log("x is equal to 10"); + } + + if (x == y) { + console.log("x is equal to y"); + } + ``` + + + +By following these performance optimization techniques and best practices, you can improve the performance of your JavaScript code and make it run faster. Remember to profile your code and identify bottlenecks before applying optimizations to ensure that you are addressing the most critical issues. + +:::info ๐Ÿš€ Performance Tip +Always measure the performance of your code before and after applying optimizations to ensure that you are achieving the desired improvements. +::: + +## Conclusion + +In this tutorial, we learned about performance optimization in JavaScript. We discussed various techniques and best practices to improve the performance of your JavaScript code, including minimizing DOM manipulation, avoiding memory leaks, optimizing loops, using event delegation, choosing efficient data structures, avoiding global variables, and using `===` instead of `==`. By following these techniques, you can optimize the performance of your JavaScript code and make it run faster. \ No newline at end of file diff --git a/languages-platforms/javascript/precedence.md b/languages-platforms/javascript/precedence.md new file mode 100644 index 0000000..9e5b9ef --- /dev/null +++ b/languages-platforms/javascript/precedence.md @@ -0,0 +1,76 @@ +--- +id: precedence-and-associativity-of-operators-in-javascript +title: Precedence and Associativity of Operators in JavaScript +sidebar_label: Precedence and Associativity of Operators +sidebar_position: 30 +tags: [JavaScript, Operators, Precedence, Associativity] +description: "In this tutorial, we will learn about the precedence and associativity of operators in JavaScript. The precedence of operators determines the order in which operators are evaluated in an expression. The associativity of operators determines the order in which operators of the same precedence are evaluated in an expression. We will see some examples to understand the precedence and associativity of operators in JavaScript." +--- + +In JavaScript, the precedence of operators determines the order in which operators are evaluated in an expression. The precedence of operators is used to determine the grouping of terms in an expression. This affects the order of evaluation of an expression. + +JavaScript follows the same precedence rules as in mathematics. The following table lists the precedence and associativity of JavaScript operators. + +| No. | Operator | Description | Associativity | +| :---: | :------- | :---------- | :------------- | +| 1 | `.` | Member Access | Left-to-right | +| 2 | `[]` | Member Access | Left-to-right | +| 3 | `()` | Function Call | Left-to-right | +| 4 | `++` `--` | Postfix Increment, Postfix Decrement | Left-to-right | +| 5 | `++` `--` | Prefix Increment, Prefix Decrement | Right-to-left | +| 6 | `!` `~` `+` `-` `typeof` `void` `delete` | Unary Operators | Right-to-left | +| 7 | `**` | Exponentiation | Right-to-left | +| 8 | `*` `/` `%` | Multiplication, Division, Remainder | Left-to-right | +| 9 | `+` `-` | Addition, Subtraction | Left-to-right | +| 10 | `<<` `>>` `>>>` | Bitwise Shifts | Left-to-right | +| 11 | `<` `<=` `>` `>=` `in` `instanceof` | Relational Operators | Left-to-right | +| 12 | `==` `!=` `===` `!==` | Equality Operators | Left-to-right | +| 13 | `&` | Bitwise AND | Left-to-right | +| 14 | `^` | Bitwise XOR | Left-to-right | +| 15 | `|` | Bitwise OR | Left-to-right | +| 16 | `&&` | Logical AND | Left-to-right | +| 17 | `||` | Logical OR | Left-to-right | +| 18 | `? :` | Conditional | Right-to-left | +| 19 | `=` `+=` `-=` `*=` `/=` `%=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` | Assignment | Right-to-left | +| 20 | `,` | Comma | Left-to-right | + +The precedence of operators determines the order in which operators are evaluated in an expression. Operators with higher precedence are evaluated first. For example, the multiplication operator `*` has a higher precedence than the addition operator `+`. So, the expression `2 + 3 * 4` is evaluated as `2 + (3 * 4)`. + +The associativity of operators determines the order in which operators of the same precedence are evaluated in an expression. For example, the addition operator `+` is left-to-right associative. So, the expression `2 + 3 + 4` is evaluated as `(2 + 3) + 4`. + +Let's see some examples to understand the precedence and associativity of operators in JavaScript. + +## Example: Precedence and Associativity of Operators + +```js title="app.js" +// Precedence and Associativity of Operators + +// Multiplication has higher precedence than addition + +let result1 = 2 + 3 * 4; // 2 + (3 * 4) = 2 + 12 = 14 + +console.log(result1); // Output: 14 + +// Addition is left-to-right associative + +let result2 = 2 + 3 + 4; // (2 + 3) + 4 = 5 + 4 = 9 + +console.log(result2); // Output: 9 +``` + +In this example, we have used the precedence and associativity of operators to evaluate the expressions `2 + 3 * 4` and `2 + 3 + 4`. + +When you run the above code, you will get the following output. + +```bash title="Output" +14 +9 +``` + +In the first expression `2 + 3 * 4`, the multiplication operator `*` has a higher precedence than the addition operator `+`. So, the expression is evaluated as `2 + (3 * 4)`, which results in `14`. + +In the second expression `2 + 3 + 4`, the addition operator `+` is left-to-right associative. So, the expression is evaluated as `(2 + 3) + 4`, which results in `9`. + +That's all for the precedence and associativity of operators in JavaScript. You can use the precedence and associativity of operators to evaluate complex expressions in JavaScript. + +I hope this tutorial helps you to understand the precedence and associativity of operators in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/random.md b/languages-platforms/javascript/random.md new file mode 100644 index 0000000..1026d91 --- /dev/null +++ b/languages-platforms/javascript/random.md @@ -0,0 +1,76 @@ +--- +id: random-in-javascript +title: Random in JavaScript +sidebar_label: Random +sidebar_position: 18 +tags: [JavaScript, Math, Object, Methods, Random, Number, Integer, Range, Floating-point, Generate, Math.random()] +description: "In this tutorial, we will learn about the Math.random() method in JavaScript. We will learn how to generate random numbers in JavaScript." +--- + +In JavaScript, the `Math.random()` method is used to generate a random floating-point number between 0 (inclusive) and 1 (exclusive). + +## Syntax + +The syntax of the `Math.random()` method is as follows: + +```js title="app.js" +Math.random() +``` + +## Example + +The following example demonstrates how to use the `Math.random()` method to generate a random number between 0 and 1: + +```js title="app.js" +console.log(Math.random()); // 0.12345678901234567 +``` + +In the above example, the `Math.random()` method returns a random floating-point number between 0 (inclusive) and 1 (exclusive). + +## Generate Random Number within a Range + +To generate a random number within a specific range, you can use the following formula: + +```js title="app.js" +Math.floor(Math.random() * (max - min + 1)) + min +``` + +Where `min` is the minimum value and `max` is the maximum value. + +The following example demonstrates how to generate a random number between 1 and 10: + +```js title="app.js" +console.log(Math.floor(Math.random() * (10 - 1 + 1)) + 1); // 5 +``` + +In the above example, the `Math.floor(Math.random() * (10 - 1 + 1)) + 1` expression generates a random number between 1 and 10. + +## Generate Random Integer + +To generate a random integer within a specific range, you can use the following formula: + +```js title="app.js" +Math.floor(Math.random() * (max - min + 1)) + min +``` + +Where `min` is the minimum value and `max` is the maximum value. + +The following example demonstrates how to generate a random integer between 1 and 10: + +```js title="app.js" +console.log(Math.floor(Math.random() * (10 - 1 + 1)) + 1); // 5 +``` + +In the above example, the `Math.floor(Math.random() * (10 - 1 + 1)) + 1` expression generates a random integer between 1 and 10. + +## A property of Math.random() method + +The `Math.random()` method returns a random floating-point number between 0 (inclusive) and 1 (exclusive). + +:::info ๐Ÿ“ Note +The `Math.random()` method returns a random number between 0 (inclusive) and 1 (exclusive). +::: + +## Conclusion + +In this tutorial, you learned how to use the `Math.random()` method to generate random numbers in JavaScript. You also learned how to generate random numbers within a specific range and how to generate random integers. \ No newline at end of file diff --git a/languages-platforms/javascript/reg-exp.md b/languages-platforms/javascript/reg-exp.md new file mode 100644 index 0000000..3042cee --- /dev/null +++ b/languages-platforms/javascript/reg-exp.md @@ -0,0 +1,395 @@ +--- +id: reg-exp-in-javascript +title: Regular Expressions in JavaScript +sidebar_label: Regular Expressions +sidebar_position: 29 +tags: [JavaScript, Regular Expressions, RegExp, Pattern, Match, Replace, Search, Split, Test, RegExp Object, RegExp Methods, RegExp Properties, RegExp in JavaScript, Regular Expressions in JavaScript, RegExp Object in JavaScript, RegExp Methods in JavaScript, RegExp Properties in JavaScript] +description: "In this tutorial, we will learn about regular expressions in JavaScript. We will learn how to create and use regular expressions to match, search, replace, and split strings in JavaScript." +--- + +In JavaScript, a regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and search-and-replace functions on strings. They are a powerful tool for working with strings and text data in JavaScript. + +## Creating a Regular Expression + +In JavaScript, you can create a regular expression using the `RegExp` object or by using a regular expression literal. + +### Using the `RegExp` Object + +You can create a regular expression using the `RegExp` object as follows: + +```js title="app.js" +const pattern = new RegExp("hello"); + +console.log(pattern); // /hello/ +``` + +In this example, we have created a regular expression that matches the string `"hello"`. +The `RegExp` object takes two arguments: the pattern and the flags. + +### Using Regular Expression Literal + +You can also create a regular expression using a regular expression literal as follows: + +```js title="app.js" +const pattern = /hello/; +``` + +In this example, we have created a regular expression using a regular expression literal. + +## Regular Expression Patterns + +A regular expression pattern is a sequence of characters that define a search pattern. It can include literal characters, metacharacters, and quantifiers. + +### Literal Characters + +Literal characters are characters that match themselves. For example, the regular expression `/hello/` matches the string `"hello"`. + +### Metacharacters + +Metacharacters are special characters that have a special meaning in regular expressions. Some common metacharacters are: + +- `.`: Matches any single character except the newline character. +- `^`: Matches the beginning of a string. +- `$`: Matches the end of a string. +- `*`: Matches zero or more occurrences of the preceding character. +- `+`: Matches one or more occurrences of the preceding character. +- `?`: Matches zero or one occurrence of the preceding character. +- `[]`: Matches any one of the characters inside the square brackets. +- `()`: Groups multiple tokens together. +- `|`: Matches either the expression before or after the `|`. +- `\`: Escapes a metacharacter or a special character. +- `{}`: Matches a specific number of occurrences of the preceding character. +- `^`: Inside square brackets, it negates the character set. +- `\b`: Matches a word boundary. +- `\B`: Matches a non-word boundary. +- `\d`: Matches a digit character. +- `\D`: Matches a non-digit character. +- `\s`: Matches a whitespace character. +- `\S`: Matches a non-whitespace character. +- `\w`: Matches a word character. +- `\W`: Matches a non-word character. +- `\n`: Matches a newline character. +- `\r`: Matches a carriage return character. +- `\t`: Matches a tab character. +- `\v`: Matches a vertical tab character. +- `\f`: Matches a form feed character. +- `\0`: Matches a null character. + +**Example for all metacharacters with their description or usage.** + +```js title="app.js" +const pattern1 = /./; // Matches any single character except the newline character +const pattern2 = /^hello/; // Matches the beginning of a string +const pattern3 = /world$/; // Matches the end of a string +const pattern4 = /a*/; // Matches zero or more occurrences of the preceding character +const pattern5 = /b+/; // Matches one or more occurrences of the preceding character +const pattern6 = /c?/; // Matches zero or one occurrence of the preceding character +const pattern7 = /[abc]/; // Matches any one of the characters inside the square brackets +const pattern8 = /(abc)/; // Groups multiple tokens together +const pattern9 = /a|b/; // Matches either the expression before or after the | +const pattern10 = /\./; // Escapes a metacharacter or a special character +const pattern11 = /d{3}/; // Matches exactly 3 occurrences of the preceding character +const pattern12 = /[^abc]/; // Negates the character set +const pattern13 = /\bword\b/; // Matches a word boundary +const pattern14 = /\d/; // Matches a digit character +const pattern15 = /\D/; // Matches a non-digit character +const pattern16 = /\s/; // Matches a whitespace character +const pattern17 = /\S/; // Matches a non-whitespace character +const pattern18 = /\w/; // Matches a word character +const pattern19 = /\W/; // Matches a non-word character +const pattern20 = /\n/; // Matches a newline character +const pattern21 = /\r/; // Matches a carriage return character +const pattern22 = /\t/; // Matches a tab character +const pattern23 = /\v/; // Matches a vertical tab character +const pattern24 = /\f/; // Matches a form feed character +const pattern25 = /\0/; // Matches a null character + +console.log(pattern1); +``` + +## Regular Expression Flags + +Regular expressions can have flags that modify the behavior of the pattern-matching. Some common flags are: + +- `i`: Case-insensitive matching. +- `g`: Global matching (find all matches). +- `m`: Multiline matching. +- `s`: Allows `.` to match newline characters. +- `u`: Enables full Unicode support. +- `y`: Sticky matching (matches from the last index). +- `d`: Enables ECMAScript 2018 mode. +- `x`: Ignores whitespace and allows comments in the pattern. +- `A`: Enables the `astral` mode. +- `D`: Enables the `dotAll` mode. +- `U`: Enables the `ungreedy` mode. +- `J`: Enables the `freeSpacing` mode. +- `X`: Enables the `extra` mode. +- `T`: Enables the `unicode` mode. +- `S`: Enables the `namedGroups` mode. +- `R`: Enables the `rightContext` mode. +- `L`: Enables the `lookbehind` mode. +- `P`: Enables the `hasIndices` mode. +- `O`: Enables the `optimize` mode. +- `C`: Enables the `constrained` mode. +- `B`: Enables the `backreferences` mode. +- `F`: Enables the `freeSpacing` mode. +- `N`: Enables the `newline` mode. +- `K`: Enables the `keepOrder` mode. +- `I`: Enables the `ignorePatternWhitespace` mode. +- `M`: Enables the `multiline` mode. +- `Y`: Enables the `sticky` mode. +- `G`: Enables the `global` mode. + +**Example for all flags with their description or usage.** + +```js title="app.js" +const pattern1 = /hello/i; // Case-insensitive matching +const pattern2 = /hello/g; // Global matching (find all matches) +const pattern3 = /hello/m; // Multiline matching +const pattern4 = /hello/s; // Allows . to match newline characters +const pattern5 = /hello/u; // Enables full Unicode support +const pattern6 = /hello/y; // Sticky matching (matches from the last index) +const pattern7 = /hello/d; // Enables ECMAScript 2018 mode +const pattern8 = /hello/x; // Ignores whitespace and allows comments in the pattern +const pattern9 = /hello/A; // Enables the astral mode +const pattern10 = /hello/D; // Enables the dotAll mode +const pattern11 = /hello/U; // Enables the ungreedy mode +const pattern12 = /hello/J; // Enables the freeSpacing mode +const pattern13 = /hello/X; // Enables the extra mode +const pattern14 = /hello/T; // Enables the unicode mode +const pattern15 = /hello/S; // Enables the namedGroups mode +const pattern16 = /hello/R; // Enables the rightContext mode + +console.log(pattern1); +``` + +## Regular Expression Methods + +In JavaScript, regular expressions are used with string methods to perform pattern-matching and search-and-replace functions on strings. Some common string methods that use regular expressions are: + +- `match()`: Returns an array of matches. +- `search()`: Returns the index of the first match. +- `replace()`: Replaces the matched substring with a new substring. +- `split()`: Splits the string into an array of substrings. +- `test()`: Tests for a match in a string. +- `exec()`: Returns the next match. +- `compile()`: Compiles a regular expression. +- `toString()`: Returns the string representation of a regular expression. +- `valueOf()`: Returns the primitive value of a regular expression. +- `toSource()`: Returns the source code of a regular expression. +- `toJSON()`: Returns the JSON representation of a regular expression. +- `toLocaleString()`: Returns the localized string representation of a regular expression. +- `hasInstance()`: Tests if a regular expression is an instance of another object. +- `isConcatSpreadable()`: Tests if a regular expression is spreadable. +- `iterator()`: Returns an iterator for a regular expression. +- `matchAll()`: Returns an iterator of matches. +- `species()`: Returns the constructor of a regular expression. +- `unscopables()`: Returns an object of properties to exclude from a regular expression. +- `flags()`: Returns the flags of a regular expression. +- `dotAll()`: Returns the dotAll flag of a regular expression. +- `sticky()`: Returns the sticky flag of a regular expression. +- `unicode()`: Returns the unicode flag of a regular expression. +- `hasIndices()`: Returns the hasIndices flag of a regular expression. +- `ignoreCase()`: Returns the ignoreCase flag of a regular expression. + +### Using the `match()` Method + +The `match()` method is used to match a string against a regular expression. It returns an array of matches if the pattern is found, or `null` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.match(pattern); + +console.log(result); // [ 'lo', index: 3, input: 'Hello, World!', groups: undefined ] +``` + +In this example, we have used the `match()` method to match the string `"Hello, World!"` against the regular expression `/lo/`. The `match()` method returns an array of matches `['lo']`. + +### Using the `search()` Method + +The `search()` method is used to search for a pattern in a string. It returns the index of the first match if the pattern is found, or `-1` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.search(pattern); + +console.log(result); // 3 +``` + +In this example, we have used the `search()` method to search for the pattern `/lo/` in the string `"Hello, World!"`. The `search()` method returns the index `3` where the pattern is found. + +### Using the `replace()` Method + +The `replace()` method is used to replace a pattern in a string with a new substring. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.replace(pattern, "123"); + +console.log(result); // He123, World! +``` + +In this example, we have used the `replace()` method to replace the pattern `/lo/` in the string `"Hello, World!"` with the new substring `"123"`. + +### Using the `split()` Method + +The `split()` method is used to split a string into an array of substrings using a regular expression or a specified separator. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.split(pattern); + +console.log(result); // [ 'He', ', World!' ] +``` + +In this example, we have used the `split()` method to split the string `"Hello, World!"` into an array of substrings using the regular expression `/lo/`. + +### Using the `test()` Method + +The `test()` method is used to test for a match in a string. It returns `true` if the pattern is found, or `false` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = pattern.test(str); + +console.log(result); // true +``` + +In this example, we have used the `test()` method to test for the pattern `/lo/` in the string `"Hello, World!"`. The `test()` method returns `true` because the pattern is found. + +### Using the `exec()` Method + +The `exec()` method is used to return the next match in a string. It returns an array of matches if the pattern is found, or `null` if the pattern is not found. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = pattern.exec(str); + +console.log(result); // [ 'lo', index: 3, input: 'Hello, World!', groups: undefined ] +``` + +In this example, we have used the `exec()` method to return the next match of the pattern `/lo/` in the string `"Hello, World!"`. The `exec()` method returns an array of matches `['lo']`. + +## Regular Expression Properties + +A regular expression object has several properties that provide information about the regular expression. + +- `source`: Returns the source text of the regular expression. +- `flags`: Returns the flags of the regular expression. +- `global`: Returns `true` if the `g` flag is set, otherwise `false`. +- `ignoreCase`: Returns `true` if the `i` flag is set, otherwise `false`. +- `multiline`: Returns `true` if the `m` flag is set, otherwise `false`. +- `dotAll`: Returns `true` if the `s` flag is set, otherwise `false`. +- `unicode`: Returns `true` if the `u` flag is set, otherwise `false`. +- `sticky`: Returns `true` if the `y` flag is set, otherwise `false`. +- `hasIndices`: Returns `true` if the `d` flag is set, otherwise `false`. + +**Example for all properties with their description or usage.** + +```js title="app.js" +const pattern = /hello/gi; + +console.log(pattern.source); // hello +console.log(pattern.flags); // gi +console.log(pattern.global); // true +console.log(pattern.ignoreCase); // true +console.log(pattern.multiline); // false +console.log(pattern.dotAll); // false +console.log(pattern.unicode); // false +console.log(pattern.sticky); // false +console.log(pattern.hasIndices); // false +``` + +In this example, we have created a regular expression `/hello/gi` and accessed its properties using the `source`, `flags`, `global`, `ignoreCase`, `multiline`, `dotAll`, `unicode`, `sticky`, and `hasIndices` properties. + +## Regular Expression Examples + +### Matching a Pattern + +You can use regular expressions to match a pattern in a string. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = pattern.test(str); + +console.log(result); // true +``` + +In this example, we have used a regular expression to match the pattern `/lo/` in the string `"Hello, World!"`. The `test()` method returns `true` because the pattern is found. + +### Searching for a Pattern + +You can use regular expressions to search for a pattern in a string. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.search(pattern); + +console.log(result); // 3 +``` + +In this example, we have used a regular expression to search for the pattern `/lo/` in the string `"Hello, World!"`. The `search()` method returns the index `3` where the pattern is found. + +### Replacing a Pattern + +You can use regular expressions to replace a pattern in a string with a new substring. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.replace(pattern, "123"); + +console.log(result); // He123, World! +``` + +In this example, we have used a regular expression to replace the pattern `/lo/` in the string `"Hello, World!"` with the new substring `"123"`. + +### Splitting a String + +You can use regular expressions to split a string into an array of substrings. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/; +const result = str.split(pattern); + +console.log(result); // [ 'He', ', World!' ] +``` + +In this example, we have used a regular expression to split the string `"Hello, World!"` into an array of substrings using the pattern `/lo/`. + +### Matching Multiple Patterns + +You can use regular expressions to match multiple patterns in a string. + +```js title="app.js" +const str = "Hello, World!"; +const pattern = /lo/g; +const result = str.match(pattern); + +console.log(result); // [ 'lo' ] +``` + +In this example, we have used a regular expression to match the pattern `/lo/g` in the string `"Hello, World!"`. The `match()` method returns an array of matches `['lo']`. + +:::tip ๐Ÿ“ Note +Regular expressions are a powerful tool for working with strings and text data in JavaScript. They are widely used in web development for tasks such as form validation, data extraction, and text processing. + +Regular expressions are a complex topic, and there are many advanced features and techniques that you can learn to become proficient in using regular expressions in JavaScript. + +In this tutorial, we have covered the basics of regular expressions in JavaScript and how to create and use regular expressions to match, search, replace, and split strings. We have also covered regular expression patterns, flags, methods, and properties. + +You can learn more about regular expressions by reading the [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and practicing with regular expressions in your own projects. +::: + +## Conclusion + +In this tutorial, you learned about regular expressions in JavaScript and how to create and use regular expressions to match, search, replace, and split strings. You also learned about regular expression patterns, flags, methods, and properties. Regular expressions are a powerful tool for working with strings and text data in JavaScript, and they are widely used in web development for tasks such as form validation, data extraction, and text processing. Regular expressions are a complex topic, and there are many advanced features and techniques that you can learn to become proficient in using regular expressions in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/scope.md b/languages-platforms/javascript/scope.md new file mode 100644 index 0000000..a3b8f8d --- /dev/null +++ b/languages-platforms/javascript/scope.md @@ -0,0 +1,144 @@ +--- +id: scopes-in-javascript +title: Scopes in JavaScript +sidebar_label: Scopes +sidebar_position: 32 +tags: [JavaScript, Scopes, Global Scope, Local Scope, Function Scope, Block Scope, Lexical Scope, Closures, Hoisting, Temporal Dead Zone, Global Object, Strict Mode, Module Scope] +description: "In this tutorial, we will learn about scopes in JavaScript. A scope is a region of a program where a variable is defined and can be accessed. We will see the different types of scopes in JavaScript and how they work." +--- + +In JavaScript, a scope is a region of a program where a variable is defined and can be accessed. JavaScript has three types of scopes: + +1. **Global Scope**: The global scope is the outermost scope in JavaScript. Variables declared outside of any function or block have global scope. Global variables can be accessed from any part of the program. +2. **Local Scope (Function Scope)**: The local scope is the innermost scope in JavaScript. Variables declared inside a function have local scope. Local variables can only be accessed from within the function in which they are declared. Each function has its own local scope. When a function is called, a new local scope is created. When the function returns, the local scope is destroyed. Local Scope is also known as Function Scope. +3. **Block Scope**: The block scope is the scope of a block of code enclosed in curly braces `{}`. Variables declared inside a block have block scope. Block scope is introduced in ECMAScript 6 (ES6) using the `let` and `const` keywords. Block scope is not available in ECMAScript 5 (ES5) and earlier versions. + +## Global Scope + +The global scope is the outermost scope in JavaScript. Variables declared outside of any function or block have global scope. Global variables can be accessed from any part of the program. For example: + +```javascript title="app.js" +let name = "Ajay Dhangar"; // Global variable + +function greet() { + console.log("Hello, " + name); // Accessing global variable +} + +greet(); // Output: Hello, Ajay Dhangar +``` + +In the above example, the variable `name` is declared outside of any function, so it has global scope. The `greet` function can access the `name` variable. + +## Local Scope (Function Scope) + +The local scope is the innermost scope in JavaScript. Variables declared inside a function have local scope. Local variables can only be accessed from within the function in which they are declared. Each function has its own local scope. When a function is called, a new local scope is created. When the function returns, the local scope is destroyed. Local Scope is also known as Function Scope. For example: + +```javascript title="app.js" +function greet() { + let message = "Hello, World!"; // Local variable + console.log(message); // Accessing local variable +} + +greet(); // Output: Hello, World! +console.log(message); // ReferenceError: message is not defined +``` + +In the above example, the variable `message` is declared inside the `greet` function, so it has local scope. The `greet` function can access the `message` variable, but it cannot be accessed outside of the function. + +## Block Scope + +The block scope is the scope of a block of code enclosed in curly braces `{}`. Variables declared inside a block have block scope. Block scope is introduced in ECMAScript 6 (ES6) using the `let` and `const` keywords. Block scope is not available in ECMAScript 5 (ES5) and earlier versions. For example: + +```javascript title="app.js" +if (true) { + let x = 10; // Block-scoped variable + console.log(x); // Accessing block-scoped variable +} + +console.log(x); // ReferenceError: x is not defined +``` + +In the above example, the variable `x` is declared inside the block of code, so it has block scope. The `x` variable can only be accessed within the block in which it is declared. It cannot be accessed outside of the block. + +## Lexical Scope + +Lexical scope is a scope in which a variable is defined at the time of writing the code. JavaScript uses lexical scope to resolve variable names. When a variable is referenced, JavaScript looks up the variable in the scope in which it was defined. If the variable is not found in the current scope, JavaScript looks up the variable in the outer scope. This process continues until the variable is found or the global scope is reached. + +Here is an example of lexical scope: + +```javascript title="app.js" +let name = "Ajay Dhangar"; // Global variable + +function greet() { + let message = "Hello, " + name; // Accessing global variable + console.log(message); +} + +greet(); // Output: Hello, Ajay Dhangar +``` + +In the above example, the `greet` function can access the `name` variable, which is defined in the global scope. This is an example of lexical scope. + +:::info ๐Ÿ“š Learn More: + +**Closures:** In JavaScript, a closure is a function that has access to its own scope, the outer function's scope, and the global scope. Closures are used to create private variables and to encapsulate functionality. Lexical scope is an important concept in understanding closures. + +Example of a closure with lexical scope for better understanding: + +```javascript title="app.js" +function outer() { + let x = 10; // Outer function variable + function inner() { + console.log(x); // Accessing outer function variable + } + return inner; +} + +let innerFunction = outer(); +innerFunction(); // Output: 10 +``` + +In this example, the `inner` function has access to the `x` variable, which is defined in the `outer` function. This is an example of a closure with lexical scope. The `inner` function has access to the `x` variable even after the `outer` function has returned. + +In the above example, the lexical scope of the `inner` function includes the scope of the `outer` function, which is why the `inner` function can access the `x` variable. This is an example of a closure with lexical scope. + +**Block Scope in ES6:** In ECMAScript 6 (ES6), the `let` and `const` keywords are introduced to declare block-scoped variables. Block scope is not available in ECMAScript 5 (ES5) and earlier versions. + +**Hoisting:** In JavaScript, variable declarations are hoisted to the top of their scope. This means that you can access a variable before it is declared. However, the value of the variable is not hoisted. Only the declaration is hoisted. + +**Temporal Dead Zone (TDZ):** In ECMAScript 6 (ES6), the `let` and `const` variables are hoisted to the top of their scope, but they are not initialized. This period between the creation of the variable and its initialization is called the Temporal Dead Zone (TDZ). If you try to access a `let` or `const` variable before it is initialized, you will get a ReferenceError. + +**Global Object:** In JavaScript, the global object is the object that holds global variables and functions. In a web browser, the global object is the `window` object. In Node.js, the global object is the `global` object. + +**Strict Mode:** In JavaScript, strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode makes it easier to write secure JavaScript code by catching common mistakes and preventing unsafe features from running. Strict mode also changes the behavior of the `this` keyword and disallows the use of undeclared variables. + +**Module Scope:** In ECMAScript 6 (ES6), JavaScript introduces the concept of modules. A module is a file that contains JavaScript code. Each module has its own scope, and the variables and functions defined in a module are not accessible outside of the module unless they are explicitly exported. + +::: + + +## Scope Chain + +The scope chain is the order in which JavaScript resolves variable names. When a variable is referenced, JavaScript looks up the variable in the scope in which it was defined. If the variable is not found in the current scope, JavaScript looks up the variable in the outer scope. This process continues until the variable is found or the global scope is reached. The scope chain is determined by the lexical scope of the code. + +Here is an example of the scope chain: + +```javascript title="app.js" +let name = "Ajay Dhangar"; // Global variable + +function greet() { + let message = "Hello, " + name; // Accessing global variable + console.log(message); +} + +greet(); // Output: Hello, Ajay Dhangar +``` + +In the above example, the `greet` function can access the `name` variable, which is defined in the global scope. This is an example of the scope chain. + + + + +## Conclusion + +In this tutorial, we learned about scopes in JavaScript. A scope is a region of a program where a variable is defined and can be accessed. JavaScript has three types of scopes: global scope, local scope (function scope), and block scope. We also learned about lexical scope, which is used by JavaScript to resolve variable names. diff --git a/languages-platforms/javascript/sets.md b/languages-platforms/javascript/sets.md new file mode 100644 index 0000000..79df9be --- /dev/null +++ b/languages-platforms/javascript/sets.md @@ -0,0 +1,195 @@ +--- +id: set-in-javascript +title: Sets in JavaScript +sidebar_label: Sets +sidebar_position: 26 +tags: + [ + JavaScript, + Set, + Data Structure, + Collection, + Unique, + Values, + Iteration, + Iterative, + Statements, + Loops, + Iteration, + Iterating, + Iterations, + Spread Operator, + Set Methods, + ] +description: "In this tutorial, we will learn about sets in JavaScript. We will learn how to use sets to store unique values in JavaScript." +--- + +In JavaScript, a `Set` is a built-in object that allows you to store unique values. It is often used when you want to store a collection of unique values without any duplicates. + +## Creating a Set + +You can create a new `Set` by using the `new` keyword followed by the `Set` constructor. You can pass an iterable + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +console.log(set); // Set { 1, 2, 3, 4, 5 } +``` + +- The `Set` constructor creates a new `Set` object. +- You can pass an iterable (such as an array) to the `Set` constructor to initialize the set with the values from the iterable. +- The `Set` object stores unique values, so any duplicate values will be removed. +- The order of elements in a `Set` is guaranteed to be the same as the order of insertion. +- The `Set` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. +- The `Set` object has a `size` property that returns the number of elements in the set. +- The `Set` object has methods to add, delete, and check for the presence of elements. +- The `Set` object does not have methods to access elements by index, as it does not maintain the order of elements. + +## Adding Elements to a Set + +You can add elements to a `Set` by using the `add` method. + +```js title="app.js" +const set = new Set(); +set.add(1); +set.add(2); +set.add(3); +console.log(set); // Set { 1, 2, 3 } +``` + +- The `add` method is used to add a new element to the set. +- If the element is already present in the set, it will not be added again. +- The `add` method returns the `Set` object, so you can chain multiple `add` calls together. +- The `add` method is chainable, so you can add multiple elements to the set in a single statement. + +## Deleting Elements from a Set + +You can delete elements from a `Set` by using the `delete` method. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +set.delete(3); +console.log(set); // Set { 1, 2, 4, 5 } +``` + +- The `delete` method is used to remove an element from the set. +- If the element is present in the set, it will be removed, and the method will return `true`. +- If the element is not present in the set, the method will return `false`. +- The `delete` method returns `true` if the element is removed, and `false` otherwise. +- The `delete` method is chainable, so you can remove multiple elements from the set in a single statement. +- The `delete` method does not throw an error if the element is not present in the set. +- The `delete` method does not return the removed element. + +## Checking for the Presence of an Element in a Set + +You can check if an element is present in a `Set` by using the `has` method. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +console.log(set.has(3)); // true +console.log(set.has(6)); // false +``` + +- The `has` method is used to check if an element is present in the set. +- If the element is present in the set, the method will return `true`. +- If the element is not present in the set, the method will return `false`. +- The `has` method is chainable, so you can check for the presence of multiple elements in a single statement. +- The `has` method does not throw an error if the element is not present in the set. +- The `has` method does not return the element itself. +- The `has` method is often used to check if a value is present in the set before adding or deleting it. + +## Iterating Over a Set + +You can iterate over the elements of a `Set` by using a `for...of` loop. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +for (const element of set) { + console.log(element); +} +``` + +The `for...of` loop is used to iterate over the elements of the set. In each iteration, the value of the current element is assigned to the loop variable `element`, and the loop body is executed. + +The output of the above example will be: + +```plaintext title="Output" +1 +2 +3 +4 +5 +``` + +In each iteration, the value of the current element is printed to the console. + +## Converting a Set to an Array + +You can convert a `Set` to an array by using the `Array.from` method or the spread operator (`...`). + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +const array = Array.from(set); +console.log(array); // [1, 2, 3, 4, 5] +``` + +- The `Array.from` method is used to create a new array from an iterable (such as a `Set`). +- The `Array.from` method returns a new array that contains the elements of the iterable. +- The spread operator (`...`) can also be used to create a new array from an iterable. +- The spread operator (`...`) returns a new array that contains the elements of the iterable. + +## Using the Set Constructor + +You can use the `Set` constructor to create an empty `Set` and then add elements to it. + +```js title="app.js" +const set = new Set(); +set.add(1); +set.add(2); +set.add(3); +console.log(set); // Set { 1, 2, 3 } +``` + +The `Set` constructor creates a new empty `Set` object. You can then use the `add` method to add elements to the set. The `Set` object stores unique values, so any duplicate values will be removed. + +## Using the Spread Operator + +You can use the spread operator (`...`) to create a new `Set` from an existing `Set`. + +```js title="app.js" +const set1 = new Set([1, 2, 3]); +const set2 = new Set([...set1, 4, 5]); +console.log(set2); // Set { 1, 2, 3, 4, 5 } +``` + +The spread operator (`...`) is used to create a new `Set` that contains the elements of an existing `Set`, as well as additional elements. The new `Set` will contain the unique values from the existing `Set` and the additional elements. + +## Using the Set Methods + +You can use the `Set` methods to add, delete, and check for the presence of elements in a `Set`. + +```js title="app.js" +const set = new Set([1, 2, 3, 4, 5]); +set.add(6); +set.delete(3); +console.log(set.has(3)); // false +``` + +The `add` method is used to add a new element to the set. The `delete` method is used to remove an element from the set. The `has` method is used to check if an element is present in the set. + +:::info ๐Ÿ“ Note + +The `Set` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. The `Set` object has a `size` property that returns the number of elements in the set. + +**1. Spread Operator:** The spread operator (`...`) can be used to create a new `Set` from an existing `Set`. The new `Set` will contain the unique values from the existing `Set and the additional elements. The spread operator can also be used to convert a `Set` to an array. + +**2. Set Methods:** The `Set` object has methods to add, delete, and check for the presence of elements. The `add` method is used to add a new element to the set. The `delete` method is used to remove an element from the set. The `has` method is used to check if an element is present in the set. + +**3. Iterating Over a Set:** The `Set` object is iterable, so you can use it in a `for...of` loop to iterate over its elements. In each iteration, the value of the current element is assigned to the loop variable, and the loop body is executed. + +**4. Converting a Set to an Array:** You can convert a `Set` to an array by using the `Array.from` method or the spread operator (`...`). The `Array.from` method is used to create a new array from an iterable, such as a `Set`. The spread operator (`...`) can also be used to create a new array from an iterable. + +::: + +## Summary + +In this tutorial, we learned about sets in JavaScript. We learned how to use sets to store unique values in JavaScript. We learned about the `Set` object and its methods for adding, deleting, and checking for the presence of elements. We also learned how to iterate over the elements of a `Set` and convert a `Set` to an array. \ No newline at end of file diff --git a/languages-platforms/javascript/statement-js.md b/languages-platforms/javascript/statement-js.md new file mode 100644 index 0000000..d0d5dd6 --- /dev/null +++ b/languages-platforms/javascript/statement-js.md @@ -0,0 +1,176 @@ +--- +id: satatement-in-js +title: Statement in JavaScript +sidebar_label: Statement in JavaScript +sidebar_position: 4 +tags: [JavaScript, Statement in JavaScript, statement in js, statement in JavaScript, JavaScript statement] +description: Write statements in JavaScript to perform different actions. Learn about different types of statements in JavaScript such as declaration statement, assignment statement, conditional statement, loop statement, function statement, return statement, break statement, continue statement, try...catch statement, and throw statement. +--- + +In this tutorial, you will learn about the statement in JavaScript. A statement is a command that performs an action. JavaScript is a scripting language, and it is executed by the browser. JavaScript statements are executed by the browser in the order they are written. + +## Types of Statements in JavaScript + +There are different types of statements in JavaScript. Some of the most commonly used statements are: + +### 1. Declaration Statement + +A declaration statement is used to declare a variable in JavaScript. For example, + +```js title="declaration-statement.js" +var name; +let age; +const PI = 3.14; +``` + +In the above program, we have declared three variables `name`, `age`, and `PI` using the `var`, `let`, and `const` keyword respectively. + +### 2. Assignment Statement + +An assignment statement is used to assign a value to a variable in JavaScript. For example, + +```js title="assignment-statement.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; +``` + +In the above program, we have assigned the value `"Ajay"` to the `name` variable, `23` to the `age` variable, and `3.14` to the `PI` variable. + +### 3. Conditional Statement + +A conditional statement is used to perform different actions based on different conditions. For example, + +```js title="conditional-statement.js" +var age = 23; + +if (age >= 18) { + console.log("You are eligible to vote."); +} else { + console.log("You are not eligible to vote."); +} +``` + +In the above program, we have used the `if...else` statement to check if the `age` is greater than or equal to `18`. If the condition is `true`, then it will print `"You are eligible to vote."`, otherwise it will print `"You are not eligible to vote."`. + +### 4. Loop Statement + +A loop statement is used to execute a block of code multiple times. For example, + +```js title="loop-statement.js" +for (var i = 1; i <= 5; i++) { + console.log(i); +} +``` + +In the above program, we have used the `for` loop to print numbers from `1` to `5`. + +### 5. Function Statement + +A function statement is used to define a function in JavaScript. For example, + +```js title="function-statement.js" +function greet() { + console.log("Hello, World!"); +} + +greet(); // Output: Hello, World! +``` + +In the above program, we have defined a function `greet()` that prints `"Hello, World!"` to the console. + +### 6. Return Statement + +A return statement is used to return a value from a function in JavaScript. For example, + +```js title="return-statement.js" +function add(a, b) { + return a + b; +} + +var sum = add(5, 3); + +console.log(sum); // Output: 8 +``` + +In the above program, we have used the `return` statement to return the sum of `a` and `b` from the `add()` function. + +### 7. Break Statement + +A break statement is used to terminate a loop in JavaScript. For example, + +```js title="break-statement.js" +for (var i = 1; i <= 5; i++) { + if (i === 3) { + break; + } + console.log(i); +} +``` + +In the above program, we have used the `break` statement to terminate the loop when `i` is equal to `3`. + +### 8. Continue Statement + +A continue statement is used to skip the current iteration of a loop in JavaScript. For example, + +```js title="continue-statement.js" + +for (var i = 1; i <= 5; i++) { + if (i === 3) { + continue; + } + console.log(i); +} +``` + +In the above program, we have used the `continue` statement to skip the iteration when `i` is equal to `3`. + +### 9. Try...Catch Statement + +A try...catch statement is used to handle errors in JavaScript. For example, + +```js title="try-catch-statement.js" +try { + var result = 10 / 0; + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); +} +``` + +In the above program, we have used the `try...catch` statement to handle the division by zero error. + +### 10. Throw Statement + +A throw statement is used to throw an exception in JavaScript. For example, + +```js title="throw-statement.js" +function divide(a, b) { + if (b === 0) { + throw new Error("Division by zero"); + } + return a / b; +} + +try { + var result = divide(10, 0); + console.log(result); +} catch (error) { + console.log("An error occurred: " + error.message); // Output: An error occurred: Division by zero +} +``` + +In the above program, we have used the `throw` statement to throw an exception when `b` is equal to `0`. + +:::info +In JavaScript, a statement is terminated by a semicolon `;`. However, it is optional in most cases. But it is a good practice to use a semicolon to terminate a statement. +::: + +## Conclusion + +In this tutorial, you have learned about the statement in JavaScript. A statement is a command that performs an action. JavaScript statements are executed by the browser in the order they are written. There are different types of statements in JavaScript such as declaration statement, assignment statement, conditional statement, loop statement, function statement, return statement, break statement, continue statement, try...catch statement, and throw statement. You can use these statements to perform different actions in JavaScript. + +I hope this tutorial will help you to understand the statement in JavaScript. + +If you have any questions or feedback, feel free to reach out to me in the comment section below. \ No newline at end of file diff --git a/languages-platforms/javascript/strict.md b/languages-platforms/javascript/strict.md new file mode 100644 index 0000000..cff98e4 --- /dev/null +++ b/languages-platforms/javascript/strict.md @@ -0,0 +1,203 @@ +--- +id: strict-mode-in-javascript +title: Strict Mode in JavaScript +sidebar_label: Strict Mode +sidebar_position: 33 +tags: [JavaScript, Strict Mode, JavaScript Strict Mode, Strict Mode in JavaScript, Use Strict, Strict Mode Tutorial, Strict Mode Guide, Strict Mode Overview, Strict Mode Basics, Strict Mode Getting Started, Strict Mode Tutorial JavaScript, Strict Mode Guide JavaScript, Strict Mode Overview JavaScript, Strict Mode Basics JavaScript, Strict Mode Getting Started JavaScript] +description: "In this tutorial, we will learn about strict mode in JavaScript. Strict mode is a feature that allows you to place a program or a function in a strict operating context. It helps catch common coding errors and makes the code more secure and optimized." +--- + +In JavaScript, strict mode is a feature that allows you to place a program or a function in a strict operating context. When strict mode is enabled, the JavaScript engine performs additional checks and enforces stricter rules on the code. This helps catch common coding errors and makes the code more secure and optimized. + +## Why Use Strict Mode? + +There are several reasons to use strict mode in JavaScript: + +1. **Catch Common Errors**: Strict mode helps catch common coding errors and unsafe actions that would otherwise go unnoticed. It throws errors for silent errors that would have been ignored in non-strict mode. +2. **Prevent Global Variables**: In strict mode, assigning a value to an undeclared variable throws an error. This helps prevent accidental creation of global variables. +3. **Optimize Code**: Strict mode enforces stricter rules on the code, which can help optimize the performance of the code and make it run faster. +4. **Improve Security**: Strict mode helps prevent certain actions that are considered unsafe or insecure in JavaScript. It makes the code more secure and less prone to vulnerabilities. +5. **Future Compatibility**: Strict mode is a standard feature of ECMAScript 5 (ES5) and later versions. Using strict mode ensures that the code is compatible with modern JavaScript environments and future versions of the language. +6. **Encourage Best Practices**: Strict mode encourages best practices and helps developers write cleaner, more maintainable code. It enforces stricter rules on variable declarations, function calls, and other aspects of the code. +7. **Enable New Features**: Some new features of JavaScript are only available in strict mode. Using strict mode allows you to take advantage of these features and write more modern and efficient code. +8. **Improve Debugging**: Strict mode helps identify and fix errors in the code more easily. It provides more informative error messages and warnings that can help developers debug the code effectively. +9. **Enhance Readability**: Strict mode makes the code more readable and self-explanatory by enforcing stricter rules on variable declarations, function calls, and other aspects of the code. +10. **Prevent Silent Failures**: Strict mode helps prevent silent failures in the code by throwing errors for common coding errors and unsafe actions. This makes the code more robust and reliable. +11. **Improve Performance**: Strict mode enforces stricter rules on the code, which can help optimize the performance of the code and make it run faster. It eliminates certain JavaScript features that are known to be slow or inefficient. +12. **Reduce Bugs**: Strict mode helps reduce the likelihood of bugs and errors in the code by enforcing stricter rules and catching common coding errors. This can save time and effort in debugging and fixing issues in the code. +13. **Enhance Code Quality**: Strict mode helps improve the quality of the code by enforcing stricter rules on variable declarations, function calls, and other aspects of the code. It encourages best practices and helps developers write cleaner, more maintainable code. + +## Enabling Strict Mode + +Strict mode can be enabled at different levels in JavaScript: + +1. **Global Strict Mode**: To enable strict mode for the entire script, you can add the `"use strict";` directive at the beginning of the script. This applies strict mode to the entire script and all functions defined within the script. + + ```javascript title="app.js" + "use strict"; + + function greet() { + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + } + + greet(); + ``` + +2. **Function Strict Mode**: To enable strict mode for a specific function, you can add the `"use strict";` directive at the beginning of the function. This applies strict mode only to the function in which it is defined. + + ```javascript title="app.js" + function greet() { + "use strict"; + + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + } + + greet(); + ``` + +3. **Module Strict Mode**: In ECMAScript 6 (ES6) and later versions, you can use strict mode in modules by default. Modules are automatically in strict mode, so you don't need to add the `"use strict";` directive explicitly. + + ```javascript title="app.js" + // app.js (module) + function greet() { + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + } + + greet(); + ``` + +When strict mode is enabled, the JavaScript engine performs additional checks and enforces stricter rules on the code. It throws errors for common coding errors and unsafe actions that would otherwise go unnoticed in non-strict mode. + +## Strict Mode Rules + +Strict mode enforces several rules on the code to catch common coding errors and make the code more secure and optimized. Some of the key rules enforced by strict mode include: + +1. **No Implicit Globals**: In strict mode, assigning a value to an undeclared variable throws an error. This helps prevent accidental creation of global variables. + + ```javascript title="app.js" + "use strict"; + + message = "Hello, World!"; // Error: Uncaught ReferenceError: message is not defined + console.log(message); + ``` + +2. **No Octal Literals**: In strict mode, octal literals (numbers with a leading zero) are not allowed. Octal literals are considered confusing and error-prone. + + ```javascript title="app.js" + "use strict"; + + let num = 010; // Error: Uncaught SyntaxError: Octal literals are not allowed in strict mode. + console.log(num); + ``` + +3. **No Duplicate Parameters**: In strict mode, defining a function with duplicate parameters throws an error. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + function greet(name, name) { // Error: Uncaught SyntaxError: Duplicate parameter name not allowed in this context + console.log("Hello, " + name); + } + + greet("Alice", "Bob"); + ``` + +4. **No `this` in Global Context**: In strict mode, the `this` keyword in the global context is `undefined`. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + console.log(this); // Output: undefined + ``` + +5. **No `eval` and `arguments`**: In strict mode, the use of `eval` and `arguments` as variable names is not allowed. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + let eval = 10; // Error: Uncaught SyntaxError: Unexpected eval or arguments in strict mode + let arguments = 20; // Error: Uncaught SyntaxError: Unexpected eval or arguments in strict mode + ``` + +6. **No `with` Statement**: In strict mode, the `with` statement is not allowed. The `with` statement is considered harmful and error-prone. + + ```javascript title="app.js" + "use strict"; + + let person = { name: "Alice" }; + with (person) { // Error: Uncaught SyntaxError: Strict mode code may not include a with statement + console.log(name); + } + ``` + +7. **No `delete` on Non-configurable Properties**: In strict mode, attempting to delete a non-configurable property throws an error. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + let obj = {}; + Object.defineProperty(obj, "name", { + value: "Alice", + configurable: false + }); + + delete obj.name; // Error: Uncaught TypeError: Cannot delete property 'name' of # + ``` + +8. **No `arguments.callee`**: In strict mode, the `arguments.callee` property is not allowed. This property is considered harmful and error-prone. + + ```javascript title="app.js" + "use strict"; + + function factorial(n) { + if (n <= 1) { + return 1; + } else { + return n * arguments.callee(n - 1); // Error: Uncaught TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them + } + } + + console.log(factorial(5)); + ``` + +9. **No `this` in Functions**: In strict mode, the `this` keyword in functions is `undefined` if the function is called without an explicit context. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + function greet() { + console.log(this); // Output: undefined + } + + greet(); + ``` + +10. **No `new` on Non-constructor Functions**: In strict mode, calling a non-constructor function with the `new` keyword throws an error. This helps prevent common coding errors and makes the code more secure. + + ```javascript title="app.js" + "use strict"; + + function greet() { + console.log("Hello, World!"); + } + + let obj = new greet(); // Error: Uncaught TypeError: greet is not a constructor + ``` + +These are some of the key rules enforced by strict mode in JavaScript. By enabling strict mode, you can catch common coding errors and make the code more secure and optimized. + +:::info ๐Ÿ“š Learn More: + +- [Strict Mode (MDN Web Docs)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode) +- [Strict Mode in JavaScript (W3Schools)](https://www.w3schools.com/js/js_strict.asp) +- [Understanding ECMAScript 6: The Definitive Guide for JavaScript Developers](https://www.amazon.com/Understanding-ECMAScript-Definitive-JavaScript-Developers/dp/1593277571) +- [JavaScript: The Good Parts](https://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742) + +::: + +## Conclusion + +Strict mode is a feature in JavaScript that allows you to place a program or a function in a strict operating context. It helps catch common coding errors and makes the code more secure and optimized. By enabling strict mode, you can enforce stricter rules on the code, prevent common coding errors, and improve the quality and performance of the code. Strict mode is a standard feature of ECMAScript 5 (ES5) and later versions, and it is recommended to use strict mode in all JavaScript code to ensure compatibility with modern JavaScript environments and future versions of the language. \ No newline at end of file diff --git a/languages-platforms/javascript/strings.md b/languages-platforms/javascript/strings.md new file mode 100644 index 0000000..3d8f892 --- /dev/null +++ b/languages-platforms/javascript/strings.md @@ -0,0 +1,331 @@ +--- +id: all-about-strings +title: All Basic About Strings in JavaScript +sidebar_label: Strings in JavaScript +sidebar_position: 13 +tags: [JavaScript, Strings, String Methods, Template Literals, Escape Characters, String Length, toUpperCase, toLowerCase, charAt, indexOf, lastIndexOf, includes, startsWith, endsWith, slice, substring, substr, replace, split, trim, concat, repeat, padStart, padEnd, match, search, localeCompare, charCodeAt, fromCharCode, fromCodePoint, codePointAt, normalize] +description: "In the JavaScript programming language, strings are text that is displayed on the screen. They are used to store and manipulate text. In this section, you will learn how to create and manipulate strings in JavaScript. You will also learn about the different methods that can be used to manipulate strings. We are going to cover the following topics in this section:" +--- + +> Strings are used to store text. They are used to represent a sequence of characters. +> Strings are written with quotes. You can use single or double quotes. + +```js title="index.js" +let name = "Ajay"; +let message = 'Hello, Ajay!'; +``` + +## String Length + +The `length` property returns the length of a string (number of characters). + +```js title="index.js" +let name = "Ajay"; +console.log(name.length); // 4 +``` + +## Escape Characters + +In JavaScript, you can use the backslash `\` to escape quotes and other characters. + +```js title="index.js" +let message = 'It\'s a beautiful day!'; +console.log(message); // It's a beautiful day! +``` + +The backslash `\` is used to escape quotes and other characters in a string. + +| Code | Output | Description | +| :--: | :----: | :---------: | +| `\'` | ' | Single quote | +| `\"` | " | Double quote | +| `\\` | \ | Backslash | +| `\n` | | New line | +| `\r` | | Carriage return | +| `\t` | | Tab | +| `\b` | | Backspace | +| `\f` | | Form feed | +| `\v` | | Vertical tab | + +## String Methods + +JavaScript has a number of built-in methods for working with strings. + +### `toUpperCase()` + +The `toUpperCase()` method converts a string to uppercase letters. + +```js title="index.js" +let name = "Ajay"; +console.log(name.toUpperCase()); // AJAY +``` + +### `toLowerCase()` + +The `toLowerCase()` method converts a string to lowercase letters. + +```js title="index.js" +let name = "AJAY"; +console.log(name.toLowerCase()); // ajay +``` + +### `charAt()` + +The `charAt()` method returns the character at a specified index (position) in a string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.charAt(0)); // A +console.log(name.charAt(1)); // j +``` + +### `indexOf()` + +The `indexOf()` method returns the position of the first occurrence of a specified value in a string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.indexOf('Ajay')); // 7 +``` + +### `lastIndexOf()` + +The `lastIndexOf()` method returns the position of the last occurrence of a specified value in a string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.lastIndexOf('l')); // 3 +``` + +### `includes()` + +The `includes()` method returns `true` if a string contains a specified value, otherwise `false`. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.includes('Ajay')); // true +console.log(message.includes('Ajayy')); // false + +// Case sensitive +console.log(message.includes('ajay')); // false +``` + +### `startsWith()` + +The `startsWith()` method returns `true` if a string starts with a specified value, otherwise `false`. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.startsWith('Hello')); // true +console.log(message.startsWith('Ajay')); // false +``` + +### `endsWith()` + +The `endsWith()` method returns `true` if a string ends with a specified value, otherwise `false`. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.endsWith('Ajay!')); // true +console.log(message.endsWith('Hello')); // false +``` + +### `slice()` + +The `slice()` method extracts a part of a string and returns the extracted part in a new string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.slice(7)); // Ajay! +console.log(message.slice(7, 11)); // Ajay +``` + +### `substring()` + +The `substring()` method extracts the characters from a string, between two specified indices, and returns the new sub string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.substring(7)); // Ajay! +console.log(message.substring(7, 11)); // Ajay +``` + +### `substr()` + +The `substr()` method extracts the characters from a string, beginning at a specified start position, and through the specified number of character. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.substr(7)); // Ajay! +console.log(message.substr(7, 4)); // Ajay +``` + +### `replace()` + +The `replace()` method replaces a specified value with another value in a string. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.replace('Ajay', 'John')); // Hello, John! +``` + +### `split()` + +The `split()` method splits a string into an array of substrings, and returns the new array. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.split(' ')); // [ 'Hello,', 'Ajay!' ] +``` + +### `trim()` + +The `trim()` method removes whitespace from both ends of a string. + +```js title="index.js" +let message = ' Hello, Ajay! '; +console.log(message.trim()); // Hello, Ajay! +``` + +### `concat()` + +The `concat()` method joins two or more strings. + +```js title="index.js" +let name = "Ajay"; +let message = 'Hello, '; +console.log(message.concat(name)); // Hello, Ajay +``` + +### `repeat()` + +The `repeat()` method returns a new string with a specified number of copies of the string it was called on. + +```js title="index.js" +let name = "Ajay"; +console.log(name.repeat(3)); // AjayAjayAjay +``` + +### `padStart()` + +The `padStart()` method pads the current string with another string until the resulting string reaches the given length. + +```js title="index.js" +let name = "Ajay"; +console.log(name.padStart(10, 'Hi ')); // Hi Hi Ajay +``` + +### `padEnd()` + +The `padEnd()` method pads the current string with another string until the resulting string reaches the given length. + +```js title="index.js" +let name = "Ajay"; +console.log(name.padEnd(10, ' Hi')); // Ajay Hi Hi +``` + +### `match()` + +The `match()` method searches a string for a match against a regular expression, and returns the matches, as an Array object. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.match('Ajay')); // [ 'Ajay', index: 7, input: 'Hello, Ajay!', groups: undefined ] +``` + +### `search()` + +The `search()` method searches a string for a specified value, and returns the position of the match. + +```js title="index.js" +let message = 'Hello, Ajay!'; +console.log(message.search('Ajay')); // 7 +``` + +### `localeCompare()` + +The `localeCompare()` method compares two strings in the current locale. + +```js title="index.js" +let name1 = "Ajay"; +let name2 = "John"; + +console.log(name1.localeCompare(name2)); // -1 +console.log(name2.localeCompare(name1)); // 1 +console.log(name1.localeCompare(name1)); // 0 +``` + +### `charCodeAt()` + +The `charCodeAt()` method returns the Unicode of the character at a specified index in a string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.charCodeAt(0)); // 65 +console.log(name.charCodeAt(1)); // 106 +``` + +### `fromCharCode()` + +The `fromCharCode()` method converts Unicode values to characters. + +```js title="index.js" +console.log(String.fromCharCode(65)); // A +console.log(String.fromCharCode(106)); // j +``` + +### `fromCodePoint()` + +The `fromCodePoint()` method returns a string created by using the specified sequence of code points. + +```js title="index.js" +console.log(String.fromCodePoint(65)); // A +console.log(String.fromCodePoint(106)); // j +``` + +### `codePointAt()` + +The `codePointAt()` method returns a non-negative integer that is the Unicode code point value. + +```js title="index.js" +let name = "Ajay"; +console.log(name.codePointAt(0)); // 65 +console.log(name.codePointAt(1)); // 106 +``` + +### `normalize()` + +The `normalize()` method returns the Unicode Normalization Form of a given string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.normalize()); // Ajay +``` + +### `includes()` + +The `includes()` method determines whether a string contains the characters of a specified string. + +```js title="index.js" +let name = "Ajay"; +console.log(name.includes('A')); // true +console.log(name.includes('a')); // false +``` + +## Template Literals + +Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 specification. + +```js title="index.js" +let name = "Ajay"; +let message = `Hello, ${name}!`; +console.log(message); // Hello, Ajay! +``` + +:::info +Template literals are enclosed by the back-tick (<) (grave accent) character instead of double or single quotes. +::: + +## Conclusion + +In this tutorial, we learned about strings in JavaScript and various methods to work with strings. We also learned about template literals. \ No newline at end of file diff --git a/languages-platforms/javascript/style-guide-js.md b/languages-platforms/javascript/style-guide-js.md new file mode 100644 index 0000000..cbbe3ec --- /dev/null +++ b/languages-platforms/javascript/style-guide-js.md @@ -0,0 +1,243 @@ +--- +id: style-guide-in-js +title: Style Guide in JavaScript +sidebar_label: Style Guide +sidebar_position: 40 +tags: + [ + JavaScript, + Style Guide, + Style Guide in JavaScript, + JavaScript Style Guide, + JavaScript Style Guide Tutorial, + JavaScript Style Guide Example, + JavaScript Style Guide Best Practices, + JavaScript Style Guide Coding Standards, + JavaScript Style Guide Recommendations, + JavaScript Style Guide Conventions, + JavaScript Style Guide Rules, + JavaScript Style Guide Linting, + JavaScript Style Guide ESLint, + JavaScript Style Guide Prettier, + JavaScript Style Guide Airbnb, + JavaScript Style Guide Google, + JavaScript Style Guide Standard, + JavaScript Style Guide AirBnB, + JavaScript Style Guide Google, + JavaScript Style Guide Standard, + JavaScript Style Guide Airbnb ESLint, + JavaScript Style Guide Google ESLint, + JavaScript Style Guide Standard ESLint, + JavaScript Style Guide Airbnb Prettier, + JavaScript Style Guide Google Prettier, + JavaScript Style Guide Standard Prettier, + JavaScript Style Guide Airbnb Linting, + JavaScript Style Guide Google Linting, + JavaScript Style Guide Standard Linting, + JavaScript Style Guide Airbnb Prettier Linting, + JavaScript Style Guide Google Prettier Linting, + JavaScript Style Guide Standard Prettier Linting, + ] +description: "In this tutorial, we will learn about the style guide in JavaScript. We will learn about the best practices, coding standards, recommendations, conventions, rules, linting, ESLint, Prettier, Airbnb, Google, Standard, AirBnB, Google, Standard, Airbnb ESLint, Google ESLint, Standard ESLint, Airbnb Prettier, Google Prettier, Standard Prettier, Airbnb Linting, Google Linting, Standard Linting, Airbnb Prettier Linting, Google Prettier Linting, Standard Prettier Linting." +--- + +Style Guide in JavaScript is a set of best practices, coding standards, recommendations, conventions, and rules that developers should follow while writing JavaScript code. It helps in maintaining the code quality, readability, and consistency across the codebase. It also helps in avoiding common pitfalls and bugs in the code. + +There are various tools available for enforcing the style guide in JavaScript such as ESLint, Prettier, Airbnb, Google, Standard, etc. These tools help in automatically checking the code against the style guide and providing suggestions or warnings to fix the issues. + +In this tutorial, we will learn about the style guide in JavaScript and how to enforce it using ESLint and Prettier. + +## Style Guide Rules + +The style guide in JavaScript consists of various rules that developers should follow while writing code. These rules cover various aspects of coding such as naming conventions, indentation, spacing, comments, etc. Some common rules in the style guide are: + +### Naming Conventions + +- Use camelCase for variable names. + + ```javascript title="Good" + let myVariable = 10; + ``` + +- Use PascalCase for class names. + + ```javascript title="Good" + class MyClass { + // class definition + } + ``` + +- Use UPPERCASE for constants. + + ```javascript title="Good" + const MY_CONSTANT = 100; + ``` + +### Indentation + +- Use 2 or 4 spaces for indentation. + + ```javascript title="Good" + function myFunction() { + if (condition) { + // code block + } + } + ``` + + ```javascript title="Good" + function myFunction() { + if (condition) { + // code block + } + + return result; + } + ``` + +### Spacing + +- Use spaces around operators. + + ```javascript title="Good" + let sum = a + b; + ``` + +- Use spaces after commas. + + ```javascript title="Good" + let arr = [1, 2, 3]; + ``` + +### Comments + +- Use comments to explain complex code or logic. + + ```javascript title="Good" + // Calculate the sum of two numbers + function sum(a, b) { + return a + b; + } + ``` + +- Avoid unnecessary comments. + + ```javascript title="Bad" + // Function to add two numbers + function sum(a, b) { + return a + b; // return sum + } + ``` + +These are just a few examples of the rules in the style guide. There are many more rules that cover different aspects of coding. + +## Linting + +Linting is the process of analyzing the code for potential errors, bugs, stylistic issues, and enforcing the style guide rules. ESLint is a popular linting tool for JavaScript that helps in identifying and fixing problems in the code. It can be configured to enforce the style guide rules and provide warnings or errors when the code violates these rules. + +To use ESLint in your project, you need to install it as a development dependency using npm or yarn. + +```bash npm2yarn +npm install eslint --save-dev +``` + +Once installed, you can create an ESLint configuration file `.eslintrc.js` in the root of your project to define the rules for your project. + +```javascript title=".eslintrc.js" +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + extends: ["eslint:recommended"], + rules: { + // add your custom rules here + }, +}; +``` + +You can also use popular ESLint configurations such as Airbnb, Google, Standard, etc., which provide a set of predefined rules that you can use in your project. + +```bash title="Install ESLint Config Airbnb" +npx install-peerdeps --dev eslint-config-airbnb +``` + +```javascript title=".eslintrc.js" +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + extends: ["airbnb"], + rules: { + // add your custom rules here + }, +}; +``` + +Once you have configured ESLint, you can run it on your project using the following command. + +```bash title="Run ESLint" +npx eslint . +``` + +ESLint will analyze your code and report any errors or warnings based on the rules defined in the configuration file. + +## Prettier + +Prettier is another popular tool for code formatting that helps in enforcing consistent code style across the codebase. It automatically formats the code according to the predefined rules such as indentation, spacing, line breaks, etc. + +To use Prettier in your project, you need to install it as a development dependency using npm or yarn. + +```bash npm2yarn +npm install prettier --save-dev +``` + +Once installed, you can create a Prettier configuration file `.prettierrc` in the root of your project to define the formatting rules. + +```json title=".prettierrc" +{ + "singleQuote": true, + "semi": false +} +``` + +You can also integrate Prettier with ESLint using the `eslint-plugin-prettier` and `eslint-config-prettier` plugins. This allows ESLint to check for formatting issues and fix them using Prettier. + +```bash npm2yarn +npm install eslint-plugin-prettier eslint-config-prettier --save-dev +``` + +```javascript title=".eslintrc.js" +module.exports = { + root: true, + env: { + node: true, + es6: true, + }, + extends: ["airbnb", "plugin:prettier/recommended"], + rules: { + // add your custom rules here + }, +}; +``` + +Once you have configured Prettier with ESLint, you can run ESLint with the `--fix` option to automatically fix the formatting issues in your code. + +```bash title="Run ESLint with Prettier" +npx eslint . --fix +``` + +This will format your code according to the Prettier rules and fix any formatting issues in the code. + +By following the style guide rules and using ESLint and Prettier, you can maintain code quality, readability, and consistency in your JavaScript projects. + +:::info +**Note:** You can also use other linting and formatting tools such as TSLint, JSHint, etc., based on your project requirements. +::: + +## Conclusion + +In this tutorial, we learned about the style guide in JavaScript and how to enforce it using ESLint and Prettier. We covered the common rules in the style guide, linting with ESLint, and code formatting with Prettier. By following the style guide rules and using these tools, you can maintain code quality, readability, and consistency in your JavaScript projects. \ No newline at end of file diff --git a/languages-platforms/javascript/switch.md b/languages-platforms/javascript/switch.md new file mode 100644 index 0000000..94eee7c --- /dev/null +++ b/languages-platforms/javascript/switch.md @@ -0,0 +1,224 @@ +--- +id: switch-in-javascript +title: Switch Statement in JavaScript +sidebar_label: Switch Statement +sidebar_position: 20 +tags: [JavaScript, Conditional, Statement, Switch, Case, Break, Default, Decision, Making, Control, Flow, Conditional, Statements] +description: "In this tutorial, we will learn about the switch statement in JavaScript. We will learn how to use the switch statement to make decisions in JavaScript." +--- + +In JavaScript, the `switch` statement is used to execute a block of code based on the value of a variable. It is an alternative to the `if...else` statement when you need to compare the value of a variable to multiple values. + +## Syntax + +The syntax of the `switch` statement is as follows: + +```js title="app.js" +switch (expression) { + case value1: + // code to be executed if expression is equal to value1 + break; + case value2: + // code to be executed if expression is equal to value2 + break; + case value3: + // code to be executed if expression is equal to value3 + break; + default: + // code to be executed if expression is different from all values +} +``` + +- The `switch` statement starts with the `switch` keyword followed by an expression in parentheses. +- The `case` keyword is followed by a value and a colon. If the value of the expression matches the value of the `case`, the code inside the `case` block is executed. +- The `break` statement is used to exit the `switch` statement. If the `break` statement is omitted, the code will continue to execute the next `case` block. +- The `default` case is optional and is executed if the value of the expression does not match any of the `case` values. +- The `default` case does not require a `break` statement because it is always the last case in the `switch` statement. +- The `default` case can be placed anywhere in the `switch` statement. + +## Flow Chart of the `switch` Statement + +```mermaid +graph TD; + Start([Start]) --> Condition{Expression}; + Condition -->|Case 1| Action1; + Condition -->|Case 2| Action2; + Condition -->|Case 3| Action3; + Condition -->|Case 4| Action4; + Condition -->|Default| DefaultAction; + Action1 --> End; + Action2 --> End; + Action3 --> End; + Action4 --> End; + DefaultAction --> End; + End --> Stop([Stop]); + +``` + +## Example + +The following example demonstrates how to use the `switch` statement to check the day of the week: + +```js title="app.js" +let day = 3; +let dayName; + +switch (day) { + case 1: + dayName = "Sunday"; + break; + case 2: + dayName = "Monday"; + break; + case 3: + dayName = "Tuesday"; + break; + case 4: + dayName = "Wednesday"; + break; + case 5: + dayName = "Thursday"; + break; + case 6: + dayName = "Friday"; + break; + case 7: + dayName = "Saturday"; + break; + default: + dayName = "Invalid day"; +} + +console.log(dayName); // Tuesday +``` + +In the above example, the `switch` statement checks the value of the `day` variable and assigns the corresponding day name to the `dayName` variable. + +:::tip Flow Chart for the Example + +```mermaid +graph TD; + Start([Start]) --> Condition{day}; + Condition -->|1| Action1; + Condition -->|2| Action2; + Condition -->|3| Action3; + Condition -->|4| Action4; + Condition -->|5| Action5; + Condition -->|6| Action6; + Condition -->|7| Action7; + Condition -->|Default| DefaultAction; + Action1 --> End; + Action2 --> End; + Action3 --> End; + Action4 --> End; + Action5 --> End; + Action6 --> End; + Action7 --> End; + DefaultAction --> End; + End --> Stop([Stop]); + + subgraph DayNames + Action1(Sunday) + Action2(Monday) + Action3(Tuesday) + Action4(Wednesday) + Action5(Thursday) + Action6(Friday) + Action7(Saturday) + DefaultAction(Invalid day) + end +``` +::: + +## Multiple Cases + +You can use multiple `case` blocks to execute the same code for different values. For example: + +```js title="app.js" +let grade = "B+"; +let message; + +switch (grade) { + case "A+": + case "A": + case "A-": + message = "Excellent"; + break; + case "B+": + case "B": + case "B-": + message = "Good"; + break; + case "C+": + case "C": + case "C-": + message = "Fair"; + break; + case "D+": + case "D": + case "D-": + message = "Poor"; + break; + case "F": + message = "Fail"; + break; + default: + message = "Invalid grade"; +} + +console.log(message); // Good +``` + +In the above example, the `switch` statement checks the value of the `grade` variable and assigns a message based on the grade. + +:::info ๐Ÿ“ Note + +

Live Example

+ +```js live +function todayIs(){ + let day = new Date().getDay(); + let dayName; + + switch (day) { + case 0: + dayName = "Sunday"; + break; + case 1: + dayName = "Monday"; + break; + case 2: + dayName = "Tuesday"; + break; + case 3: + dayName = "Wednesday"; + break; + case 4: + dayName = "Thursday"; + break; + case 5: + dayName = "Friday"; + break; + case 6: + dayName = "Saturday"; + break; + default: + dayName = "Invalid day"; + } + + return ( +
+

Today is {dayName}

+
+ ) +} + +``` + +In the above example, the `switch` statement checks the value of the `day` variable and assigns the corresponding day name to the `dayName` variable. + +::: + +## Conclusion + +In this tutorial, you learned about the `switch` statement in JavaScript and how to use it to make decisions based on the value of a variable. You also learned how to use multiple `case` blocks to execute the same code for different values. \ No newline at end of file diff --git a/languages-platforms/javascript/syntax-js-.md b/languages-platforms/javascript/syntax-js-.md new file mode 100644 index 0000000..f1501e2 --- /dev/null +++ b/languages-platforms/javascript/syntax-js-.md @@ -0,0 +1,243 @@ +--- +id: syntax-of-js +title: Syntax of JavaScript +sidebar_label: Syntax of JavaScript +sidebar_position: 5 +tags: [JavaScript, Syntax of JavaScript, syntax of js, syntax of JavaScript, JavaScript syntax] +description: Write a JavaScript program using the syntax of JavaScript. Learn about the syntax of JavaScript, how to create a JavaScript file, how to create variables, how to use variables, how to create and use functions, JavaScript values, operators, literals, keywords, comments, statements, expressions, identifiers, naming conventions, case sensitivity, and the JavaScript character set. +--- + +In this tutorial, you will learn about the syntax of JavaScript. The syntax of JavaScript is the set of rules that define how a JavaScript program will be written and interpreted. The syntax of JavaScript is similar to the syntax of other programming languages like C, C++, and Java. + +## Hello, World! Program in JavaScript + +Let's start with a simple "Hello, World!" program in JavaScript. + +```js title="HelloWorld.js" +console.log("Hello, World!"); +``` + +In the above program, we have used the `console.log()` method to print "Hello, World!" to the console. + +## How to create a JavaScript file? + +You can create a JavaScript file with a `.js` extension. For example, `HelloWorld.js`. + +## How to create variables in JavaScript? + +You can create variables in JavaScript using the `var`, `let`, or `const` keyword. For example, + +```js title="variables.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; +``` + +In the above program, we have created three variables `name`, `age`, and `PI` using the `var`, `let`, and `const` keyword respectively. + +## How to use variables in JavaScript? + +You can use variables in JavaScript to store and manipulate data. For example, + +```js title="use-variables.js" +var name = "Ajay"; +console.log(name); // Output: Ajay + +let age = 23; + +age = age + 1; + +console.log(age); // Output: 24 +``` + +In the above program, we have used the `name` and `age` variables to store and manipulate data. + +## How to create and use functions in JavaScript? + +You can create and use functions in JavaScript to perform a specific task. Functions is created using the `function` keyword. For example, + +```js title="functions.js" +function greet() { + console.log("Hello, World!"); +} + +greet(); // Output: Hello, World! +``` + +In the above program, we have created a function `greet()` that prints "Hello, World!" to the console. + +## JavaScript Values + +JavaScript values are the data that is stored in variables. For example, `10`, `"Hello, World!"`, `true`, `false`, etc. + +for example, + +```js title="values.js" +var num = 10; +var name = "Ajay"; +var isStudent = true; +``` + +## JavaScript Operators + +JavaScript operators are used to perform operations on variables and values. For example, `+`, `-`, `*`, `/`, `==`, `!=`, `>`, `<`, etc. + +For example, + +```js title="operators.js" +var num1 = 10; +var num2 = 20; + +var sum = num1 + num2; +console.log(sum); // Output: 30 + +var isGreater = num1 > num2; +console.log(isGreater); // Output: false +``` + +## JavaScript Literals + +JavaScript literals are fixed values that are directly written in the code. For example, `10`, `"Hello, World!"`, `true`, `false`, etc. + +For example, + +```js title="literals.js" +console.log(10); // Output: 10 +console.log("Hello, World!"); // Output: Hello, World! +console.log(true); // Output: true +``` + +## JavaScript Keywords + +JavaScript keywords are the reserved words that have a special meaning in JavaScript. For example, `var`, `let`, `const`, `function`, `if`, `else`, `for`, `while`, etc. + +For example, + +```js title="keywords.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; + +if (age > 18) { + console.log("You are an adult!"); +} else { + console.log("You are a child!"); +} +``` + +## JavaScript Comments + +JavaScript comments are used to explain the code and make it more readable. There are two types of comments in JavaScript: single-line comments and multi-line comments. + +For example, + +```js title="comments.js" + +// This is a single-line comment + +/* +This is a multi-line comment +It can span multiple lines +*/ +``` + +## JavaScript Statements + +JavaScript statements are the instructions that are executed by the browser. For example, variable declaration, conditional statement, loop statement, function statement, etc. + +For example, + +```js title="statements.js" +var name = "Ajay"; +let age = 23; +const PI = 3.14; + +if (age > 18) { + console.log("You are an adult!"); +} else { + console.log("You are a child!"); +} +``` + +In the above program, we have declared variables `name`, `age`, and `PI` using the `var`, `let`, and `const` keyword respectively. We have also used the `if...else` statement to check if the `age` is greater than `18`. + +## JavaScript Expressions + +JavaScript expressions are the combination of values, variables, and operators that are evaluated to produce a value. For example, `10 + 20`, `name + " is " + age + " years old"`, etc. + +For example, + +```js title="expressions.js" +var num1 = 10; +var num2 = 20; + +var sum = num1 + num2; + +var name = "Ajay"; +let age = 23; + +var message = name + " is " + age + " years old."; +``` + +In the above program, `num1 + num2` and `name + " is " + age + " years old"` are expressions. + +## JavaScript Identifiers, Naming Conventions, and Case Sensitivity + +JavaScript identifiers are the names given to variables, functions, labels, and objects. JavaScript identifiers are case-sensitive and can contain letters, digits, underscores, and dollar signs. + +A JavaScript name must start with: + +- A letter (A-Z or a-z) +- A dollar sign ($) +- Or an underscore (_) +- After the first letter, a JavaScript name can also contain digits (0-9). +- JavaScript names are case-sensitive. + +For example, + +```js title="identifiers.js" +var name = "Ajay"; +let Age = 23; +const $currency = "USD"; +const _PI = 3.14; +const isStudent = true; +const surname123 = "Dhangar"; +``` + +In the above program, `name`, `Age`, `$currency`, `_PI`, `isStudent`, and `surname123` are identifiers. + +## JavaScript Character Set + +JavaScript uses the Unicode character set. JavaScript supports both ASCII and Unicode characters. + +for example, + +```js title="character-set.js" +var name = "Ajay"; +var โ‚น = "Rupee"; +var ใ“ใ‚“ใซใกใฏ = "Hello"; +``` + +In the above program, `name`, `โ‚น`, and `ใ“ใ‚“ใซใกใฏ` are identifiers. + +:::warning +- JavaScript identifiers should not start with a digit (0-9). + for example, + ```js title="invalid-identifiers.js" + var 123name = "Ajay"; // Invalid + ``` +- JavaScript identifiers should not contain special characters except `$` and `_`. + for example, + ```js title="invalid-identifiers.js" + var first-name = "Ajay"; // Invalid + ``` +- JavaScript identifiers should not be a JavaScript keyword. + for example, + ```js title="invalid-identifiers.js" + var var = "Ajay"; // Invalid + ``` +::: + +## Conclusion + +In this tutorial, you have learned about the syntax of JavaScript. The syntax of JavaScript is the set of rules that define how a JavaScript program will be written and interpreted. The syntax of JavaScript is similar to the syntax of other programming languages like C, C++, and Java. You have also learned about the "Hello, World!" program, how to create a JavaScript file, how to create variables, how to use variables, how to create and use functions, JavaScript values, operators, literals, keywords, comments, statements, expressions, identifiers, naming conventions, case sensitivity, and the JavaScript character set. \ No newline at end of file diff --git a/languages-platforms/javascript/this-keyword.md b/languages-platforms/javascript/this-keyword.md new file mode 100644 index 0000000..07ea7ad --- /dev/null +++ b/languages-platforms/javascript/this-keyword.md @@ -0,0 +1,760 @@ +--- +id: this-keyword-in-javascript +title: this Keyword in JavaScript +sidebar_label: this Keyword +sidebar_position: 34 +tags: [JavaScript, this, this keyword, this binding, this value, this context, this in functions, this in methods, this in constructors, this in arrow functions, this in event handlers, this in callbacks, this in nested functions, this in global scope, this in strict mode, this in modules, this in classes, this in prototypes, this in async functions, this in promises, this in generators, this in iterators, this in destructuring, this in spread operator, this in rest parameters, this in default parameters, this in computed properties, this in dynamic properties, this in getters, this in setters, this in static methods, this in private methods, this in public methods, this in protected methods, this in instance methods, this in static properties, this in private properties, this in public properties, this in protected properties, this in instance properties, this in static accessors, this in private accessors] +description: "In this tutorial, we will learn about the `this` keyword in JavaScript. The `this` keyword refers to the object on which a function is being invoked. The value of `this` depends on how a function is called. We will see how `this` works in different contexts such as functions, methods, constructors, arrow functions, event handlers, callbacks, nested functions, global scope, strict mode, modules, classes, prototypes, async functions, promises, generators, iterators, destructuring, spread operator, rest parameters, default parameters, computed properties, dynamic properties, getters, setters, static methods, private methods, public methods, protected methods, instance methods, static properties, private properties, public properties, protected properties, instance properties, static accessors, private accessors, etc." +--- + +In JavaScript, the `this` keyword refers to the object on which a function is being invoked. The value of `this` depends on how a function is called. The `this` keyword allows you to access the object's properties and methods from within the function. + +The `this` keyword is a special keyword in JavaScript that is used to refer to the object on which a function is being invoked. The value of `this` is determined by how a function is called, not where it is defined. The `this` keyword allows you to access the object's properties and methods from within the function. + +The `this` keyword can be used in different contexts such as functions, methods, constructors, arrow functions, event handlers, callbacks, nested functions, global scope, strict mode, modules, classes, prototypes, async functions, promises, generators, iterators, destructuring, spread operator, rest parameters, default parameters, computed properties, dynamic properties, getters, setters, static methods, private methods, public methods, protected methods, instance methods, static properties, private properties, public properties, protected properties, instance properties, static accessors, private accessors, etc. + +In this tutorial, we will learn how the `this` keyword works in different contexts in JavaScript. + +## `this` in Functions + +In JavaScript, the `this` keyword in a function refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +function greet() { + console.log(this); // Output: Window {...} (in browsers) +} + +greet(); +``` + +In the above example, the `this` keyword inside the `greet` function refers to the global object (`Window` in browsers) because the `greet` function is called in the global scope. + +## `this` in Methods + +In JavaScript, the `this` keyword in a method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet() { + console.log(this.name); // Output: Alice + } +}; + +person.greet(); +``` + +In the above example, the `this` keyword inside the `greet` method of the `person` object refers to the `person` object because the `greet` method is called on the `person` object. + +## `this` in Constructors + +In JavaScript, the `this` keyword in a constructor refers to the object being created by the constructor. + +For example: + +```javascript title="app.js" +function Person(name) { + this.name = name; + this.greet = function() { + console.log("Hello, " + this.name); + }; +} + +const person = new Person("Alice"); +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the `Person` constructor refers to the object being created by the constructor. The `this.name` property of the object is set to the `name` argument passed to the constructor. + +## `this` in Arrow Functions + +In JavaScript, the `this` keyword in an arrow function refers to the `this` value of the enclosing lexical context. Arrow functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet: function() { + const greetArrow = () => { + console.log(this.name); // Output: Alice + }; + + greetArrow(); + } +}; + +person.greet(); +``` + +In the above example, the `this` keyword inside the arrow function `greetArrow` refers to the `this` value of the `greet` method of the `person` object because the arrow function does not have its own `this` value. + +## `this` in Event Handlers + +In JavaScript, the `this` keyword in an event handler refers to the element that triggered the event. + +For example: + +```html title="index.html" + + + + + Event Handler + + + + + + + +``` + + + + + +In the above example, the `this` keyword inside the event handler function refers to the `button` element that triggered the `click` event. + +## `this` in Callbacks + +In JavaScript, the `this` keyword in a callback function refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +function greet(callback) { + callback(); +} + +function sayHello() { + console.log(this); // Output: Window {...} (in browsers) +} + +greet(sayHello); +``` + +In the above example, the `this` keyword inside the `sayHello` callback function refers to the global object (`Window` in browsers) because the `sayHello` function is called in the global scope. + +## `this` in Nested Functions + +In JavaScript, the `this` keyword in a nested function refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +function outer() { + function inner() { + console.log(this); // Output: Window {...} (in browsers) + } + + inner(); +} + +outer(); +``` + +In the above example, the `this` keyword inside the `inner` nested function refers to the global object (`Window` in browsers) because the `inner` function is called in the global scope. + +## `this` in Global Scope + +In JavaScript, the `this` keyword in the global scope refers to the global object (`window` in browsers, `global` in Node.js). + +For example: + +```javascript title="app.js" +console.log(this); // Output: Window {...} (in browsers) +``` + +In the above example, the `this` keyword in the global scope refers to the global object (`Window` in browsers). + +## `this` in Strict Mode + +In JavaScript, the `this` keyword in the global scope refers to `undefined` in strict mode. + +For example: + +```javascript title="app.js" +"use strict"; + +console.log(this); // Output: undefined +``` + +In the above example, the `this` keyword in the global scope refers to `undefined` because the code is running in strict mode. + +## `this` in Modules + +In JavaScript, the `this` keyword in a module refers to `undefined` in strict mode. + +For example: + +```javascript title="app.js" +console.log(this); // Output: undefined +``` + +```html title="index.html" + + + + + + Module + + + + + +``` + +In the above example, the `this` keyword in the module `app.js` refers to `undefined` because the code is running in strict mode. + +## `this` in Classes + +In JavaScript, the `this` keyword in a class method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the `greet` method of the `Person` class refers to the `person` object because the `greet` method is called on the `person` object. + +## `this` in Prototypes + +In JavaScript, the `this` keyword in a prototype method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +function Person(name) { + this.name = name; +} + +Person.prototype.greet = function() { + console.log("Hello, " + this.name); +}; + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the `greet` prototype method of the `Person` constructor refers to the `person` object because the `greet` method is called on the `person` object. + +## `this` in Async Functions + +In JavaScript, the `this` keyword in an async function refers to the `this` value of the enclosing lexical context. Async functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet: async function() { + console.log(this.name); // Output: Alice + } +}; + +person.greet(); +``` + +In the above example, the `this` keyword inside the async function `greet` refers to the `this` value of the `person` object because async functions do not have their own `this` value. + +## `this` in Promises + +In JavaScript, the `this` keyword in a promise callback refers to the global object (`window` in browsers, `global` in Node.js) when the function is called in the global scope. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet: function() { + return new Promise((resolve, reject) => { + resolve(this.name); + }); + } +}; + +person.greet().then(name => { + console.log(name); // Output: Alice +}); +``` + +In the above example, the `this` keyword inside the promise callback refers to the global object (`Window` in browsers) because the promise callback is called in the global scope. + +## `this` in Generators + +In JavaScript, the `this` keyword in a generator function refers to the `this` value of the enclosing lexical context. Generator functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + *greet() { + console.log(this.name); // Output: Alice + } +}; + +const generator = person.greet(); + +generator.next(); +``` + +In the above example, the `this` keyword inside the generator function `greet` refers to the `this` value of the `person` object because generator functions do not have their own `this` value. + +## `this` in Iterators + +In JavaScript, the `this` keyword in an iterator function refers to the `this` value of the enclosing lexical context. Iterator functions do not have their own `this` value. Instead, they inherit the `this` value from the surrounding code. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + [Symbol.iterator]: function*() { + yield this.name; + } +}; + +for (const name of person) { + console.log(name); // Output: Alice +} +``` + +In the above example, the `this` keyword inside the iterator function refers to the `this` value of the `person` object because iterator functions do not have their own `this` value. + +## `this` in Destructuring + +In JavaScript, the `this` keyword in a destructuring assignment refers to the global object (`window` in browsers, `global` in Node.js) when the assignment is done in the global scope. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice" +}; + +const { name } = person; + +console.log(this); // Output: Window {...} (in browsers) +``` + +In the above example, the `this` keyword inside the destructuring assignment refers to the global object (`Window` in browsers) because the assignment is done in the global scope. + +## `this` in Spread Operator + +In JavaScript, the `this` keyword in a spread operator refers to the global object (`window` in browsers, `global` in Node.js) when the operator is used in the global scope. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice" +}; + +const personCopy = { ...person }; + +console.log(this); // Output: Window {...} (in browsers) +``` + +In the above example, the `this` keyword inside the spread operator refers to the global object (`Window` in browsers) because the operator is used in the global scope. + +## `this` in Rest Parameters + +In JavaScript, the `this` keyword in a rest parameter refers to the global object (`window` in browsers, `global` in Node.js) when the parameter is used in the global scope. + +For example: + +```javascript title="app.js" +function greet(...args) { + console.log(this); // Output: Window {...} (in browsers) +} + +greet("Alice", "Bob"); +``` + +In the above example, the `this` keyword inside the rest parameter refers to the global object (`Window` in browsers) because the parameter is used in the global scope. + +## `this` in Default Parameters + +In JavaScript, the `this` keyword in a default parameter refers to the global object (`window` in browsers, `global` in Node.js) when the parameter is used in the global scope. + +For example: + +```javascript title="app.js" +function greet(name = "Alice") { + console.log(this); // Output: Window {...} (in browsers) +} + +greet(); +``` + +In the above example, the `this` keyword inside the default parameter refers to the global object (`Window` in browsers) because the parameter is used in the global scope. + +## `this` in Computed Properties + +In JavaScript, the `this` keyword in a computed property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + ["greet"]() { + console.log("Hello, " + this.name); + } +}; + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the computed property `greet` refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Dynamic Properties + +In JavaScript, the `this` keyword in a dynamic property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + greet() { + console.log("Hello, " + this.name); + } +}; + +person["greet"](); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the dynamic property `greet` refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Getters + +In JavaScript, the `this` keyword in a getter refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" +const person = { + name: "Alice", + get greeting() { + return "Hello, " + this.name; + } +}; + +console.log(person.greeting); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the getter `greeting` refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Setters + +In JavaScript, the `this` keyword in a setter refers to the object on which the property is being set. + +For example: + +```javascript title="app.js" +const person = { + _name: "", + set name(value) { + this._name = value; + }, + get name() { + return this._name; + } +}; + +person.name = "Alice"; + +console.log(person.name); // Output: Alice +``` + +In the above example, the `this` keyword inside the setter `name` refers to the `person` object because the property is set on the `person` object. + +## `this` in Static Methods + +In JavaScript, the `this` keyword in a static method refers to the class itself, not an instance of the class. + +For example: + +```javascript title="app.js" +class Person { + static greet() { + console.log("Hello, world"); + } +} + +Person.greet(); // Output: Hello, world +``` + +In the above example, the `this` keyword inside the static method `greet` refers to the `Person` class itself, not an instance of the class. + +## `this` in Private Methods + +In JavaScript, the `this` keyword in a private method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + #name; + + constructor(name) { + this.#name = name; + } + + #greet() { + console.log("Hello, " + this.#name); + } + + greet() { + this.#greet(); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the private method `#greet` of the `Person` class refers to the `person` object because the private method is called on the `person` object. + +## `this` in Public Methods + +In JavaScript, the `this` keyword in a public method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the public method `greet` of the `Person` class refers to the `person` object because the public method is called on the `person` object. + +## `this` in Protected Methods + +In JavaScript, the `this` keyword in a protected method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + #greet() { + console.log("Hello, " + this.name); + } + + greet() { + this.#greet(); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the protected method `#greet` of the `Person` class refers to the `person` object because the protected method is called on the `person` object. + +## `this` in Instance Methods + +In JavaScript, the `this` keyword in an instance method refers to the object on which the method is being invoked. + +For example: + +```javascript title="app.js" +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the instance method `greet` of the `Person` class refers to the `person` object because the instance method is called on the `person` object. + +## `this` in Static Properties + +In JavaScript, the `this` keyword in a static property refers to the class itself, not an instance of the class. + +For example: + +```javascript title="app.js" +class Person { + static name = "Alice"; + + static greet() { + console.log("Hello, " + this.name); + } +} + +Person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the static property `name` of the `Person` class refers to the `Person` class itself, not an instance of the class. + +## `this` in Private Properties + +In JavaScript, the `this` keyword in a private property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" + +class Person { + #name; + + constructor(name) { + this.#name = name; + } + + greet() { + console.log("Hello, " + this.#name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the private property `#name` of the `Person` class refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Public Properties + +In JavaScript, the `this` keyword in a public property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" + +class Person { + constructor(name) { + this.name = name; + } + + greet() { + console.log("Hello, " + this.name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the public property `name` of the `Person` class refers to the `person` object because the property is accessed on the `person` object. + +## `this` in Protected Properties + +In JavaScript, the `this` keyword in a protected property refers to the object on which the property is being accessed. + +For example: + +```javascript title="app.js" + +class Person { + #name; + + constructor(name) { + this.#name = name; + } + + greet() { + console.log("Hello, " + this.#name); + } +} + +const person = new Person("Alice"); + +person.greet(); // Output: Hello, Alice +``` + +In the above example, the `this` keyword inside the protected property `#name` of the `Person` class refers to the `person` object because the property is accessed on the `person` object. + + +## `this` in Static Accessors + +In JavaScript, the `this` keyword in a static accessor refers to the class itself, not an instance of the class. + +For example: + +```javascript title="app.js" +class Person { + static #name = "Alice"; + + static get name() { + return this.#name; + } + + static set name(value) { + this.#name = value; + } +} + +console.log(Person.name); // Output: Alice + +Person.name = "Bob"; + +console.log(Person.name); // Output: Bob +``` + +In the above example, the `this` keyword inside the static accessor `name` of the `Person` class refers to the `Person` class itself, not an instance of the class. + +:::info ๐Ÿค–๐Ÿ‹๏ธโ€โ™‚๏ธ + +The `this` keyword in JavaScript is a powerful feature that allows you to access the object's properties and methods from within a function. The value of `this` depends on how a function is called. By understanding how `this` works in different contexts, you can write more flexible and reusable code. + +::: + +## Conclusion + +In this tutorial, we have learned about the `this` keyword in JavaScript. The `this` keyword refers to the object on which a function is being invoked. The value of `this` depends on how a function is called. We have seen how `this` works in different contexts such as functions, methods, constructors, arrow functions, event handlers, callbacks, nested functions, global scope, strict mode, modules, classes, prototypes, async functions, promises, generators, iterators, destructuring, spread operator, rest parameters, default parameters, computed properties, dynamic properties, getters, setters, static methods, private methods, public methods, protected methods, instance methods, static properties, private properties, public properties, protected properties, static accessors, etc. \ No newline at end of file diff --git a/languages-platforms/javascript/type-of.md b/languages-platforms/javascript/type-of.md new file mode 100644 index 0000000..c54526b --- /dev/null +++ b/languages-platforms/javascript/type-of.md @@ -0,0 +1,130 @@ +--- +id: type-of-in-javascript +title: typeof Operator in JavaScript +sidebar_label: typeof +sidebar_position: 28 +tags: [JavaScript, typeof, Operator, Type, Value, Data, Typeof, Typeof Operator, Typeof Keyword, Typeof Operator in JavaScript, Typeof Keyword in JavaScript, Typeof Operator, Typeof Keyword, Typeof Operator in JS, Typeof Keyword in JS] +description: "In this tutorial, we will learn about the typeof operator in JavaScript. We will learn how to use the typeof operator to determine the type of a value in JavaScript." +--- + +In JavaScript, the `typeof` operator is used to determine the type of a value. It is often used when you want to check the type of a variable or a value before performing an operation on it. + +## Syntax + +The syntax of the `typeof` operator is as follows: + +```js title="app.js" +typeof value +``` + +- The `typeof` operator is followed by the `value` whose type you want to determine. +- The `value` can be a variable, a literal, or an expression. +- The `typeof` operator returns a string that represents the type of the `value`. +- The returned string can be one of the following values: + - `"undefined"`: If the `value` is `undefined`. + - `"boolean"`: If the `value` is a boolean. + - `"number"`: If the `value` is a number. + - `"string"`: If the `value` is a string. + - `"symbol"`: If the `value` is a symbol. + - `"function"`: If the `value` is a function. + - `"object"`: If the `value` is an object or `null`. + - `"bigint"`: If the `value` is a BigInt. + - `"object"`: If the `value` is an object or `null`. + +## Example + +The following example demonstrates how to use the `typeof` operator to determine the type of a value: + +```js title="app.js" +const name = "John"; +const age = 30; +const isMarried = false; +const fruits = ["apple", "banana", "cherry"]; +const person = { + name: "John", + age: 30, +}; + +console.log(typeof name); // string +console.log(typeof age); // number +console.log(typeof isMarried); // boolean +console.log(typeof fruits); // object +console.log(typeof person); // object +console.log(typeof undefinedVariable); // undefined +console.log(typeof nullVariable); // object +``` + +- In this example, we have used the `typeof` operator to determine the type of different values such as strings, numbers, booleans, arrays, objects, `undefined`, and `null`. +- The `typeof` operator returns the type of the value as a string. +- The `typeof` operator is often used to check the type of a value before performing an operation on it, such as type conversion or type-specific operations. +- The `typeof` operator is useful when you want to handle different types of values differently in your code. +- The `typeof` operator can be used to determine the type of a variable or a value at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a value before performing an operation on it, such as type conversion or type-specific operations. +- The `typeof` operator can be used to handle different types of values differently in your code. +- The `typeof` operator can be used to determine the type of a variable or a value at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a value before performing an operation on it, such as type conversion or type-specific operations. + +## Using the `typeof` Operator with Functions + +The `typeof` operator can be used to determine the type of a function. It returns `"function"` if the value is a function. + +```js title="app.js" +function greet() { + console.log("Hello, World!"); +} + +console.log(typeof greet); // function +``` + +- In this example, we have used the `typeof` operator to determine the type of the `greet` function. +- The `typeof` operator returns `"function"` because the `greet` value is a function. +- The `typeof` operator can be used to determine the type of a function, which can be useful when you want to handle functions differently in your code. +- The `typeof` operator can be used to determine the type of a function at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a function before performing an operation on it, such as calling the function or passing it as an argument to another function. +- The `typeof` operator can be used to handle functions differently in your code based on their type. + +## Using the `typeof` Operator with `null` + +The `typeof` operator returns `"object"` if the value is `null`. This is a historical bug in JavaScript, and it is not expected to change. + +```js title="app.js" +const person = null; + +console.log(typeof person); // object +``` + +In this example, we have used the `typeof` operator to determine the type of the `person` value, which is `null`. The `typeof` operator returns `"object"` because the `person` value is `null`. + +The `typeof` operator returns `"object"` if the value is `null`. This is a historical bug in JavaScript, and it is not expected to change. + +The `typeof` operator can be used to determine the type of a value at runtime, which can be useful in dynamic programming scenarios. + +The `typeof` operator can be used to determine the type of a value before performing an operation on it, such as type conversion or type-specific operations. + + +## Using the `typeof` Operator with Symbols + +The `typeof` operator returns `"symbol"` if the value is a symbol. + +```js title="app.js" +const symbol = Symbol("mySymbol"); + +console.log(typeof symbol); // symbol +``` + +- In this example, we have used the `typeof` operator to determine the type of the `symbol` value, which is a symbol. +- The `typeof` operator returns `"symbol"` because the `symbol` value is a symbol. +- The `typeof` operator can be used to determine the type of a symbol, which can be useful when you want to handle symbols differently in your code. +- The `typeof` operator can be used to determine the type of a symbol at runtime, which can be useful in dynamic programming scenarios. +- The `typeof` operator can be used to determine the type of a symbol before performing an operation on it, such as type conversion or type-specific operations. +- The `typeof` operator can be used to handle symbols differently in your code based on their type. + +:::caution + +The `typeof` operator returns `"object"` if the value is `null`. This is a historical bug in JavaScript, and it is not expected to change. + +::: + +## Conclusion + +In this tutorial, you learned about the `typeof` operator in JavaScript and how to use it to determine the type of a value. You also learned about the different types of values that the `typeof` operator can return, such as `"undefined"`, `"boolean"`, `"number"`, `"string"`, `"symbol"`, `"function"`, `"object"`, and `"bigint"`. You also learned about the historical bug in JavaScript where the `typeof` operator returns `"object"` for `null` values. The `typeof` operator is useful when you want to handle different types of values differently in your code, and it can be used to determine the type of a variable or a value at runtime, which can be useful in dynamic programming scenarios. \ No newline at end of file diff --git a/languages-platforms/javascript/variables-js.md b/languages-platforms/javascript/variables-js.md new file mode 100644 index 0000000..811c023 --- /dev/null +++ b/languages-platforms/javascript/variables-js.md @@ -0,0 +1,303 @@ +--- +id: variables-in-javascript +title: Variables in JavaScript +sidebar_label: Variables in JavaScript +sidebar_position: 7 +tags: [JavaScript, Variables, variables in js] +description: What are variables in JavaScript? How to declare and initialize variables in JavaScript? Learn about variable naming rules and best practices. +--- + +In this tutorial, you will learn about variables in JavaScript. Variables are used to store data. They are like containers that hold data. You can think of them as a box that holds different items. You can put anything in the box and give it a name. Similarly, you can store different types of data in a variable and give it a name. + +## What are Variables? + +A variable is a named storage location that holds data. It has a name and a value. The value of a variable can change during the execution of a program. + +```mermaid +graph LR; + A[Variables] --> B(Containers for storing data); + B --> C(Data can be of different types, such as numbers, strings, booleans, etc.); + B --> D(Data can be assigned, retrieved, and modified); + B --> E(Variables have a name or identifier); + B --> F(Variables can have different scopes, such as global scope or local scope); +``` + +In JavaScript, you can declare a variable using the `var`, `let`, or `const` keyword. + +## Declaring Variables + +You can declare a variable using the `var`, `let`, or `const` keyword followed by the variable name. + +```mermaid +sequenceDiagram + participant User + participant Interpreter + participant Memory + + User->>Interpreter: Declare Variables + Interpreter->>User: Choose a name for the variable + Interpreter->>User: Determine the data type + Interpreter->>User: Use the appropriate keyword to declare the variable + Interpreter->>User: Optionally assign an initial value to the variable + Interpreter->>Memory: Allocate memory for the variable + Interpreter->>Interpreter: Store variable name and data type in symbol table + Interpreter->>User: Variable declaration completed + +``` + +For example, + +```js title="declaring-variables.js" +var name; +let age; +const PI = 3.14; +``` + +In this example, we have declared three variables: `name`, `age`, and `PI`. The `var` and `let` keywords are used to declare variables. The `const` keyword is used to declare constants. + +:::important +The `var` keyword is used to declare variables in JavaScript. However, it is recommended to use `let` and `const` instead of `var` to declare variables. We will learn more about `let` and `const` in the upcoming sections. +::: + +## Initializing Variables + +You can initialize a variable at the time of declaration. To initialize a variable, you can assign a value to it using the assignment operator (`=`). + +```mermaid +sequenceDiagram + participant User + participant Interpreter + participant Memory + + User->>Interpreter: Initialize Variables + Interpreter->>User: Provide initial values for variables + Interpreter->>Memory: Assign initial values to variables in memory + Interpreter->>User: Initialization completed +``` + +For example, + +```js title="initializing-variables.js" +var name = "John"; +let age = 25; +const PI = 3.14; +``` + +In this example, we have initialized three variables: `name`, `age`, and `PI`. The `name` variable is initialized with the value `"John"`, the `age` variable is initialized with the value `25`, and the `PI` constant is initialized with the value `3.14`. + +## Variable Naming Rules + +```mermaid +flowchart LR; + Start --> A[Variable Naming Rules]; + A --> B{Start with Letter, Underscore or Dollar Sign }; + B --> |Yes| C[Continue with Letters, Digits, Underscores, or Dollar Signs]; + C --> D{Not Start with Digit}; + D --> |Yes| E[Not Reserved Keywords]; + E --> F{Follow Naming Convention}; + F --> |Yes| G[Valid Variable Name]; + B --> |No| H[Invalid Variable Name]; + D --> |No| H; + E --> |No| H; + H --> I{Error or Warning}; + I --> J[Review and Correct]; +``` + +When naming variables in JavaScript, there are a few rules you need to follow: + +1. The variable name must start with a letter, underscore (`_`), or dollar sign (`$`). +2. The variable name can contain letters, digits, underscores (`_`), or dollar signs (`$`). +3. The variable name cannot contain spaces or special characters, except underscores (`_`) or dollar signs (`$`). +4. The variable name is case-sensitive. For example, `name`, `Name`, and `NAME` are three different variables. +5. The variable name should be descriptive and meaningful. +6. The variable name should not be a reserved keyword. +7. The variable name should follow camelCase or snake_case naming convention. +8. The variable name should not start with a capital letter. +9. The variable name should not be too long or too short. +10. The variable name should not be a JavaScript built-in object, method, or property. + +## Best Practices for Naming Variables + +```mermaid +flowchart LR; + Start --> A[Best Practices for Naming Variables]; + A --> B[Use descriptive names]; + A --> C[Use camelCase]; + A --> D[Avoid abbreviations]; + A --> E[Be consistent]; + A --> F[Avoid single-letter names]; + A --> G[Avoid reserved keywords]; + B --> H{Descriptive}; + H --> |Yes| I[Good]; + H --> |No| J[Improve]; + J --> K{Improve}; + K --> |Yes| I; + K --> |No| J; + I --> L{CamelCase}; + L --> |Yes| M[Good]; + L --> |No| N[Improve]; + N --> O{Improve}; + O --> |Yes| M; + O --> |No| N; + E --> P{Consistency}; + P --> |Yes| Q[Good]; + P --> |No| R[Improve]; + R --> S{Improve}; + S --> |Yes| Q; + S --> |No| R; + F --> T{Single-letter}; + T --> |Yes| U[Improve]; + T --> |No| V[Good]; + U --> W{Improve}; + W --> |Yes| V; + W --> |No| U; + G --> X{Reserved Keywords}; + X --> |Yes| Y[Avoided]; + X --> |No| Z[Good]; +``` + +When naming variables in JavaScript, you should follow these best practices: + +1. Use descriptive and meaningful variable names. + for example, `firstName`, `lastName`, `age`, `email`, `address`, etc. +2. Use camelCase or snake_case naming convention. + for example, `firstName`, `last_name`, `userAge`, `user_email`, etc. +3. Do not use reserved keywords as variable names. + for example, `var`, `let`, `const`, `function`, `if`, `else`, `while`, `for`, etc. +4. Do not use JavaScript built-in objects, methods, or properties as variable names. + for example, `Math`, `Date`, `String`, `Number`, `Object`, `Array`, `console`, `log`, `error`, etc. +5. Do not use a single character as a variable name. + for example, `a`, `b`, `c`, `x`, `y`, `z`, etc. +6. Do not use a too long or too short variable name. + for example, `thisIsAVeryLongVariableName`, `a`, `b`, etc. + +## Differents between var, let, and const in JavaScript + +In JavaScript, you can declare a variable using the `var`, `let`, or `const` keyword. Each keyword has different behavior and scope. + +| Keyword | Scope | Hoisting |TDZ | Re-declaration | Re-assignment | Mutable | +|:-------:|:-----:|:--------:|:--:|:--------------:|:-------------:|:-------:| +| var | Function | Yes | No | Yes | Yes | Yes | +| let | Block | No | Yes | No | Yes | Yes | +| const | Block | No | Yes | No | No | No | + +- **Scope**: The scope of a variable is the region of the program where the variable is accessible. The scope of a variable can be global or local. The `var` keyword has a function scope, while the `let` and `const` keywords have a block scope. + + for example, + + ```js title="scope.js" + var x = 10; + let y = 20; + const z = 30; + + function test() { + var a = 40; + let b = 50; + const c = 60; + console.log(a, b, c); // 40 50 60 + } + + console.log(x, y, z); // 10 20 30 + console.log(a, b, c); // ReferenceError: a is not defined + ``` + +- **Hoisting**: Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase. The `var` keyword is hoisted, while the `let` and `const` keywords are not hoisted. + + for example, + + ```js title="hoisting.js" + console.log(x); // undefined + var x = 10; + ``` + +- **Temporal Dead Zone (TDZ)**: The temporal dead zone is a behavior in JavaScript where you cannot access a variable before it is declared. The `let` and `const` keywords have a temporal dead zone, while the `var` keyword does not have a temporal dead zone. + + for example, + + ```js title="tdz.js" + console.log(x); // ReferenceError: Cannot access 'x' before initialization + let x = 10; + ``` + +- **Re-declaration**: The `var` keyword allows you to re-declare a variable in the same scope, while the `let` and `const` keywords do not allow you to re-declare a variable in the same scope. + + for example, + + ```js title="re-declaration.js" + var x = 10; + var x = 20; + console.log(x); // 20 + + let y = 30; + let y = 40; // SyntaxError: Identifier 'y' has already been declared + ``` + +- **Re-assignment**: The `var`, `let`, and `const` keywords allow you to re-assign a value to a variable. However, the `const` keyword does not allow you to re-assign a value to a variable. + + for example, + + ```js title="re-assignment.js" + var x = 10; + x = 20; + console.log(x); // 20 + + let y = 30; + y = 40; + console.log(y); // 40 + + const z = 50; + z = 60; // TypeError: Assignment to constant variable. + ``` + +- **Mutable**: The `var` and `let` keywords allow you to mutate the value of a variable, while the `const` keyword does not allow you to mutate the value of a variable. + + for example, + + ```js title="mutable.js" + var x = 10; + x = 20; + console.log(x); // 20 + + let y = 30; + y = 40; + console.log(y); // 40 + + const z = 50; + z = 60; // TypeError: Assignment to constant variable. + ``` + + ```mermaid + graph TD; + A[Variables] --> B{Scope}; + B --> |var| C[Function]; + B --> |let| D[Block]; + B --> |const| E[Block]; + A --> F{Hoisting}; + F --> |var| G[Yes]; + F --> |let| H[No]; + F --> |const| I[No]; + A --> J{Temporal Dead Zone}; + J --> |var| K[No]; + J --> |let| L[Yes]; + J --> |const| M[Yes]; + A --> N{Re-declaration}; + N --> |var| O[Yes]; + N --> |let| P[No]; + N --> |const| Q[No]; + A --> R{Re-assignment}; + R --> |var| S[Yes]; + R --> |let| T[Yes]; + R --> |const| U[No]; + A --> V{Mutable}; + V --> |var| W[Yes]; + V --> |let| X[Yes]; + V --> |const| Y[No]; + ``` + +:::important +It is recommended to use `let` and `const` instead of `var` to declare variables. Use `let` when you want to declare a variable that can be re-assigned, and use `const` when you want to declare a variable that cannot be re-assigned. +::: + +## Conclusion + +In this tutorial, you learned about variables in JavaScript. You learned what variables are, how to declare and initialize variables, and the rules and best practices for naming variables. In the next tutorial, you will learn about data types in JavaScript. \ No newline at end of file diff --git a/languages-platforms/javascript/where-to-js.md b/languages-platforms/javascript/where-to-js.md new file mode 100644 index 0000000..d5d4f24 --- /dev/null +++ b/languages-platforms/javascript/where-to-js.md @@ -0,0 +1,100 @@ +--- +id: where-to-js +title: Where to Write JavaScript +sidebar_label: Where to JavaScript +sidebar_position: 2 +tags: [JavaScript, Introduction of js, Introduction of JavaScript, Where to javascript ] +description: Where to write JavaScript code? Learn about the different places where JavaScript code can be written such as inline JavaScript, internal JavaScript, and external JavaScript. +--- + +JavaScript code can be written in three places: + +### 1. Inline JavaScript + +JavaScript code can be written directly in an HTML file in the HTML element's attribute. For example, in the `onclick` attribute of a button element. + +```html + + + + Inline JavaScript + + + + + +``` + + + + + +### 2. Internal JavaScript + +JavaScript code can be written in the ` + + + + + +``` + + + + + +### 3. External JavaScript + +JavaScript code can be written in an external file with a `.js` extension. The external JavaScript file can be linked to the HTML file using the ` + + + + + +``` + +```js title="script.js" +function sayHello() { + alert('Hello World!'); +} +``` + + + + + +:::tip + +1. It is recommended to write JavaScript code in an external file to separate the structure of the HTML file from the behavior of the web page. This makes the code more organized and easier to maintain. + +2. It helps to keep the HTML file clean and easy to read. It also allows the JavaScript code to be reused in multiple HTML files. + +3. The external JavaScript file should be linked to the HTML file using the `