Skip to content
the poor coder

WHAT IS Shorthan IN JAVASCRIPT ?

Poor Man
Published
Reading time
2 min read
On this page

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:#

Text

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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC