Javascript fundamentals
Strict Mode
In JavaScript, strict mode is a way to opt into a more restricted variant of JavaScript, where the language imposes stricter parsing and error handling on your code. It helps catch common coding mistakes and unsafe actions, improving code quality and performance. You can enable strict mode by adding the string"use strict";
at the beginning of a script or a function.
Advantages of strict mode -
i) Prevents the use of undeclared variablesWithout strict mode, if you assign a value to an undeclared variable, JavaScript will automatically create it as a global variable. In strict mode, this would throw an error.
"use strict"; x = 5; // Throws an error: x is not declared // it should be either var, const or let
ii) Disallows duplicate parameter names
In non-strict mode, you can define a function with duplicate parameter names. Strict mode disallows this as it leads to confusing code.
"use strict"; function sum(a, a) { // Throws an error: duplicate parameter names not allowed return a + a; }
Benefits of Using Strict Mode -
i) Helps avoid common mistakes, such as implicit globals.
ii) Improves performance as some JavaScript engines can optimize strict-mode code better.
iii) Makes your code more predictable and easier to debug.
iv) Encourages adherence to best practices.
Strict mode can be applied at the global level or at the function level.
It is not allowed in block-level scopes like
if
orfor
loops.Data Types
i) Primitive Data Types - Number, bigInt, String, Boolean, null, undefined, NaN
ii) Reference Data Types - Array, Objects and SymbolsThe typeof operator returns the type of the argument.
Type Conversions - Number(value), String(value)Truthy and Falsy values - Values that are intuitively “empty”, like 0, an empty string, null, undefined, and NaN, become false. These values are called falsy value. Other than these values are called Truthy values.
Global Variables - Variables declared outside of any function, are called global variables. Global variables are visible from any function (unless shadowed or re-initialise by locals). It’s a good practice to minimise the use of global variables. Modern code has few or no global.
Template Literals
Template literals, introduced in ECMAScript 6 (ES6), are a way to work with strings in JavaScript in a more flexible and expressive manner. They allow you to embed expressions and multi line strings directly within the string syntax, using back ticks (`).const name = 'John'; const age = 30; // Using template literals const greeting = `Hello, my name is ${name} and I am ${age} years old.`; console.log(greeting);
In this example, the ${} syntax within the back ticks allows you to embed variables directly into the string. This is known as string interpolation.
Template literals can contain any valid JavaScript expression within
${}
. This can include variable references, mathematical operations, function calls, and more:const a = 5; const b = 10; const result = `The sum of ${a} and ${b} is ${a + b}`; console.log(result);
JSON
In JavaScript, JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. JavaScript provides built-in methods for working with JSON, which are primarily available through the JSON object. Here are some common JSON methods in JavaScript,
i) JSON.stringifyThis method is used to convert a JavaScript object into a JSON string.
const obj = { name: "John", age: 30, city: "New York" }; const jsonString = JSON.stringify(obj); console.log(jsonString);
ii) JSON.parse
This method is used to parse a JSON string and convert it into a JavaScript object.
const jsonString = '{"name":"John","age":30,"city":"New York"}'; const parsedObj = JSON.parse(jsonString); console.log(parsedObj);
Chaining Methods
In JavaScript, chaining methods is a technique used to execute multiple methods on an object in a single statement, one after the other. This can make your code more concise and readable. Chaining is commonly used with methods that return the object itself (this
) after performing an operation, allowing you to call another method on the result.let string = "hello"; // Chaining string methods let result = string.toUpperCase().split('').reverse().join(''); console.log(result); // Output: "OLLEH"
Strings
In JavaScript, a string is a sequence of characters enclosed within single (' '), double (" "), or backticks (` ) quotes. Here are some key features and operations related to strings in JavaScript.const airline= 'Tap Air Portugal'; console.log( airline.length ); // OUTPUT : 16 console.log( airline.indexOf('p'); // OUTPUT : 2 console.log( airline.slice(4) ); // OUTPUT : Air Portugal console.log( airline.slice(4, 7) ); // OUTPUT : Air console.log( airline.slice( -2 ) ); // OUTPUT : al console.log( airline.toLowerCase() ); // OUTPUT : tap air portugal console.log( airline.toUpperCase() ); // OUTPUT : TAP AIR PORTUGAL console.log( airline.trim() ); console.log( airline.trimLeft() ); console.log( airline.trimRight() ); console.log( airline.replace('a' 'b') ); // OUTPUT : Tbp Bir Portugbl console.log( airline.replace( 'Port' ); // OUTPUT : True // it checks the substring exists or not in the main string console.log( airline.split(' ') ); // OUTPUT : Array[ 'Tap', 'Air', 'Portugal' ]; const airline= 'Tap Air Portugal'; consloe.log( airline.split(' ') ); // OUTPUT : Array[ 'Tap', 'Air', 'Portugal' ]; const ArrAirline = [ 'tap', 'air', 'portugal' ]; console.log( ArrAirLine.join(' ') ); // OUTPUT : 'tap air portugal'
Local Storage
localStorage
in JavaScript is an API that allows you to store key-value pairs locally in a web browser. It provides a simple way to persist data across browser sessions. Disadvantage of localStorage is that the persistent storage scoped to an origin rather than a domain, it cannot be accessed from different domains or even subdomains.
Here's how you can uselocalStorage
,
i) Setting ValuelocalStorage.setItem('key', 'value');
ii) Getting Value
var value = localStorage.getItem('key');
iii) Removing the value
localStorage.removeItem('key');
iv) Clearing all Values
localStorage.clear();
localStorage
stores data as string. So, when you store an object, it will be converted to a string. To store and retrieve objects, you can useJSON.stringify
andJSON.parse
,var obj = { name: 'John', age: 30 }; localStorage.setItem('person', JSON.stringify(obj)); var storedObj = JSON.parse(localStorage.getItem('person'));
Keep in mind that
localStorage
is synchronous, and the data stored persists even after the browser is closed and reopened, until explicitly cleared or removed by the user. However, note that the storage size is limited (usually around 5-10 MB per domain), and it's not suitable for storing sensitive information due to its accessibility via JavaScript.