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 shorthand let x = 5; or const 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 shorthand x && doSomething();. This is because the expression x && doSomething() evaluates to true only if both x is true and doSomething() returns a truthy value.
  • Ternary Operator: Instead of writing if (x === true) {y = 'yes';} else {y = 'no';}, we can use the shorthand y = 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 shorthand function foo(x = 5) {return x;}. This means that if the parameter x 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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe