WHAT IS Shorthan IN JAVASCRIPT ?
What is Shorthand in JavaScript?
In JavaScript, shorthand is a way of writing code that helps to simplify and reduce the amount of code that needs to be written. It involves using shorter syntax to achieve the same outcome.
Examples of Shorthand in JavaScript
- Variable Declaration: Instead of writing
var x = 5;
, we can use the shorthandlet x = 5;
orconst x = 5;
depending on whether we want to declare a variable that can be reassigned or not. - Conditional Statements: Instead of writing
if (x === true) {doSomething();}
, we can use the shorthandx && doSomething();
. This is because the expressionx && doSomething()
evaluates to true only if bothx
is true anddoSomething()
returns a truthy value. - Ternary Operator: Instead of writing
if (x === true) {y = 'yes';} else {y = 'no';}
, we can use the shorthandy = x ? 'yes' : 'no';
. This is because the ternary operator evaluates the expression before the question mark and returns the value after the question mark if the expression is true, and the value after the colon if it is false. - Default Parameter: Instead of writing
function foo(x) {if (x === undefined) {x = 5;} return x;}
, we can use the shorthandfunction foo(x = 5) {return x;}
. This means that if the parameterx
is not passed into the function, it will default to 5.
Code Example:
let x = 5;
let y = true;
// Conditional Statement shorthand
x === 5 && console.log("x is 5"); // prints "x is 5"
y && console.log("y is true"); // prints "y is true"
// Ternary Operator shorthand
let z = x === 5 ? "yes" : "no";
console.log(z); // prints "yes"
// Default Parameter shorthand
function foo(x = 10) {
return x;
}
console.log(foo()); // prints 10
These are just a few examples of the many ways shorthand can be used in JavaScript to simplify code. By using shorthand, code becomes more readable, easier to understand, and quicker to write.