How to Shorten JavaScript Code and Operators

A beginner tutorial

Ivan Cabral
Dec 7, 2019 · 2 min read

We can shorten the JavaScript code to make fewer lines in the code and today I show you some of this shortcuts, first open Google Chrome and open the inspector and got to the console for typing

Operators

An operator is a symbol that tells the compiler or interpreter to perform a specific mathematical, relational or logical operations and produce a final result.

If conditionals

The conditional ternary operator in JavaScript assigns a value to a variable based on some condition and is the only JavaScript operator that takes three operands.

Normal code

let valueOne = “”
If (true == false) {
valueOne = “is true”
} else {
valueOne = “is false”
}
console.log(valueOne)

Shortened Code

let valueOne = true == false? “is true”: “is false
console.log(valueOne)

Result:

For Conditional

Normal code

let valueArray = [ “a”, “b”, “c”, “d”, “e”, “f”, “g” ]
for (let i=0; i< valueArray.length; i++){
console.log(valueArray[”i”] + ” - position: ”+ i)
}

Shortened Code

let valueArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
valueArray.forEach((val, index) => console.log(val + “ - position: ”+index) )

Result:

Simple demo combining this tutorial

In this demo, we change the lost for the dollar flying

let bank = [“💵”, “📉”, “💷”, “💴”, “💶”,”💰”]
bank.forEach((b, index) => {
console.log(index !== 1? b : “💸”)
})

Thank you for seeing my story! If you like my stories follow me or clap my story so you support me to continue publishing my knowledge

JavaScript in Plain English

Learn the web's most important programming language.

Ivan Cabral

Written by

I‘m a daily coder FullStack developer with more than 10 years of experience, creator of gambling web sites, writer for JavaScript and Cryptocurrencies

JavaScript in Plain English

Learn the web's most important programming language.

More From Medium

More from JavaScript in Plain English

More from JavaScript in Plain English

More from JavaScript in Plain English

5 Secret features of JSON.stringify()

More from JavaScript in Plain English

More from JavaScript in Plain English

7 really good reasons not to use TypeScript

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade