Skip to main content

Command Palette

Search for a command to run...

Top JavaScript Shorthands Techniques

Published
•2 min read•View as Markdown
Top JavaScript Shorthands Techniques
M

PHP developer. I share with you what I learn.

Hello Everyone, in this article you will see Top JavaScript Shorthands Techniques to speed up your tasks

1. Declare more than one variable in one line

  • Normal method
let a = 1;
let b = 2;
let c = 3;
  • Short method
let a=1,b=2,c=3;

2. The Ternary Operator

if you want to write if else statement in one line you can use the ternary operator

  • Normal method
let x = 30

if(x > 20){
    console.log("greater than 20")
}
else {
    console.log("less than 20")
}
  • Short method
let x = 12;
    x>10 ? console.log("greater than 20") : console.log("less than 20")

3. Set variable values in one line

  • Normal method
let a = 1;
let b = 2;
let c = 3;
  • Short method
let [a,b,c ] = [1,2,3]

5. JavaScript For Loop

  • Normal method
let languages = ["JS","Python","PHP"]
    for(let i = 0 ; i<languages.length ; i++){
        console.log(languages[i])
}
  • Short method
for (let language of languages){
        console.log(language)
}

If you just wanted to access the index :

for (let language in languages){
        console.log(language)
}

6. Object Property Assign Shorthand

this shorthand work if the variable name is the same as the object key

  • Normal method
 let name = "mostafa";
 let age = 17;
 let myinfo = {
        name : name,
        age : age
    };
  • Short method
 let name = "mostafa";
 let age = 17;
let myinfo = {name, age}

7. swapping variables

  • Normal method
 let a = 20;
let b = 30;

let temp = a;
a = b
b = temp
  • Short method
let a = 20;
let b = 30;
[a,b] = [b,a]

Thank you for reaching the end. See you in another article ❤️