Top 35 JavaScript Shorthands for Beginners

JavaScript shorthands not only speed up the coding process but also make scripts shorter, therefore lead to faster page loads

This post really is a must read for any JavaScript developer. I have written this guide to shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on, I have included the longhand versions to give some coding perspective.

1. The Ternary Operator

This is a great code saver when you want to write an if..else statement in just one line.

Longhand:

const x = 20;
let answer;

if (x > 10) {
    answer = "greater than 10";
} else {
    answer =  "less than 10";
}

Shorthand:

const answer = x > 10 ? "greater than 10" : "less than 10";

You can also nest your if statement like this:

const answer = x > 10 ? "greater than 10" : x < 5 ? "less than 5" : "between 5 and 10";

let someThingTrue = true
if(someThingTrue){
    console.log(“its true”)
}else{
    console.log(“its not true”)
}
****** Short Hand version below ******
let someThingTrue = true
someThingTrue ? console.log(“its true”) : console.log(“its not true”)

2. Short-circuit Evaluation Shorthand

When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty. You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation.

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}

Shorthand:

const variable2 = variable1  || 'new';

Don’t believe me? Test it yourself (paste the following code in es6console):

let variable1;
let variable2 = variable1  || 'bar';
console.log(variable2 === 'bar'); // prints true

variable1 = 'foo';
variable2 = variable1  || 'bar';
console.log(variable2); // prints foo

Do note that if you set variable1 to false or 0, the value bar will be assigned.

var someValueNotSureOfItsExistance = null
var expectingSomeValue = someValueNotSureOfItsExistance || “Value”

3. Declaring Variables Shorthand

It’s good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.

Longhand:

let x;
let y;
let z = 3;

Shorthand:

let x, y, z=3;

4. If Presence Shorthand

This might be trivial, but worth a mention. When doing “if checks”, assignment operators can sometimes be omitted.

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

Note: these two examples are not exactly equal, as the shorthand check will pass as long as likeJavaScript is a truthy value.

Here is another example. If a is NOT equal to true, then do something.

Longhand:

let a;
if ( a !== true ) {
// do something...
}

Shorthand:

let a;
if ( !a ) {
// do something...
}

5. JavaScript For Loop Shorthand

This little tip is really useful if you want plain JavaScript and don’t want to rely on external libraries such as jQuery or lodash.

Longhand:

const fruits = ['mango', 'peach', 'banana'];
for (let i = 0; i < fruits.length; i++)

Shorthand:

for (let fruit of fruits)

If you just wanted to access the index, do:

for (let index in fruits)

This also works if you want to access keys in a literal object:

const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
for (let key in obj)
  console.log(key) // output: continent, country, city

Shorthand for Array.forEach:

function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = 9

6. Short-circuit Evaluation

Instead of writing six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code.

Longhand:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}

Shorthand:

const dbHost = process.env.DB_HOST || 'localhost';

7. Decimal Base Exponents

You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e7 essentially means 1 followed by 7 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 10,000,000.

Longhand:

for (let i = 0; i < 10000; i++) {}

Shorthand:

for (let i = 0; i < 1e7; i++) {}

// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

8. Object Property Shorthand

Defining object literals in JavaScript makes life much easier. ES6 provides an even easier way of assigning properties to objects. If the variable name is the same as the object key, you can take advantage of the shorthand notation.

Longhand:

const x = 1920, y = 1080;
const obj = { x:x, y:y };

Shorthand:

const obj = { x, y };

9. Arrow Functions Shorthand

Classical functions are easy to read and write in their plain form, but they do tend to become a bit verbose and confusing once you start nesting them in other function calls.

Longhand:

function sayHello(name) {
  console.log('Hello', name);
}

setTimeout(function() {
  console.log('Loaded')
}, 2000);

list.forEach(function(item) {
  console.log(item);
});

Shorthand:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

It’s important to note that the value of this inside an arrow function is determined differently than for longhand functions, so the two examples are not strictly equivalent. See this article on arrow function syntax for more details.

10. Implicit Return Shorthand

Return is a keyword we use often to return the final result of a function. An arrow function with a single statement will implicitly return the result its evaluation (the function must omit the braces ({}) in order to omit the return keyword).

To return a multi-line statement (such as an object literal), it’s necessary to use () instead of {} to wrap your function body. This ensures the code is evaluated as a single statement.

Longhand:

function calcCircumference(diameter) {
  return Math.PI * diameter
}

Shorthand:

calcCircumference = diameter => (
  Math.PI * diameter;
)

11. Default Parameter Values

You can use the if statement to define default values for function parameters. In ES6, you can define the default values in the function declaration itself.

Longhand:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

Shorthand:

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) //output: 24

12. Template Literals

Aren’t you tired of using ' + ' to concatenate multiple variables into a string? Isn’t there a much easier way of doing this? If you are able to use ES6, then you are in luck. All you need to do is use is the backtick, and ${} to enclose your variables.

Longhand:

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

Shorthand:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

13. Destructuring Assignment Shorthand

If you are working with any popular web framework, there are high chances you will be using arrays or data in the form of object literals to pass information between components and APIs. Once the data object reaches a component, you’ll need to unpack it.

Longhand:

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

Shorthand:

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

You can even assign your own variable names:

const { store, form, loading, errors, entity:contact } = this.props;

14. Multi-line String Shorthand

If you have ever found yourself in need of writing multi-line strings in code, this is how you would write it:

Longhand:

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

But there is an easier way. Just use backticks.

Shorthand:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

15. Spread Operator Shorthand

The spread operator, introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.

Longhand

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

Shorthand:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

Unlike the concat() function, you can use the spread operator to insert an array anywhere inside another array.

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

You can also combine the spread operator with ES6 destructuring notation:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16. Mandatory Parameter Shorthand

By default, JavaScript will set function parameters to undefined if they are not passed a value. Some other languages will throw a warning or error. To enforce parameter assignment, you can use an if statement to throw an error if undefined, or you can take advantage of the ‘Mandatory parameter shorthand’.

Longhand:

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

Shorthand:

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}

17. Array.find Shorthand

If you have ever been tasked with writing a find function in plain JavaScript, you would probably have used a for loop. In ES6, a new array function named find() was introduced.

Longhand:

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

Shorthand:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18. Object [key] Shorthand

Did you know that Foo.bar can also be written as Foo['bar']? At first, there doesn’t seem to be a reason why you should write it like that. However, this notation gives you the building block for writing re-usable code.

Consider this simplified example of a validation function:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

This function does its job perfectly. However, consider a scenario where you have very many forms where you need to apply the validation but with different fields and rules. Wouldn’t it be nice to build a generic validation function that can be configured at runtime?

Shorthand:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}

console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

Now we have a validate function we can reuse in all forms without needing to write a custom validation function for each.

19. Double Bitwise NOT Shorthand

Bitwise operators are one of those features you learn about in beginner JavaScript tutorials and you never get to implement them anywhere. Besides, who wants to work with ones and zeroes if you are not dealing with binary?

There is, however, a very practical use case for the Double Bitwise NOT operator. You can use it as a replacement for Math.floor(). The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can read more about Bitwise operators here.

Longhand:

Math.floor(4.9) === 4  //true

Shorthand:

~~4.9 === 4  //true

20. Exponent Power Shorthand

Shorthand for a Math exponent power function:

Longhand:

Math.pow(2,3); // 8
Math.pow(2,2); // 4
Math.pow(4,3); // 64

Shorthand:

2**3 // 8
2**4 // 4
4**3 // 64

21. Converting a String into a Number

There are times when your code receives data that comes in String format but needs to processed in Numerical format. It’s not a big deal, we can perform a quick conversion.

Longhand:

const num1 = parseInt("100");
const num2 =  parseFloat("100.01");

Shorthand:

const num1 = +"100"; // converts to int data type
const num2 =  +"100.01"; // converts to float data type

22. Object Property Assignment

Consider the following piece of code:

let fname = { firstName : 'Black' };
let lname = { lastName : 'Panther'}

How would you merge them into one object? One way is to write a function that copies data from the second object onto the first one. Unfortunately, this might not be what you want — you may need to create an entirely new object without mutating any of the existing objects. The easiest way is to use the Object.assign function introduced in ES6:

let full_names = Object.assign(fname, lname);

You can also use the object destruction notation introduced in ES8:

let full_names = {...fname, ...lname};

There is no limit to the number of object properties you can merge. If you do have objects with identical property names, values will be overwritten in the order they were merged.

23. Bitwise IndexOf Shorthand

When performing a lookup using an array, the indexOf() function is used to retrieve the position of the item you are looking for. If the item is not found, the value -1 is returned. In JavaScript, 0 is considered ‘falsy’, while numbers greater or lesser than 0 are considered ‘truthy’. As a result, one has to write the correct code like this.

Longhand:

if(arr.indexOf(item) > -1) { // Confirm item IS found

}

if(arr.indexOf(item) === -1) { // Confirm item IS NOT found

}

Shorthand:

if(~arr.indexOf(item)) { // Confirm item IS found

}

if(!~arr.indexOf(item)) { // Confirm item IS NOT found

}

The bitwise(~) operator will return a truthy value for anything but -1. Negating it is as simple as doing !~. Alternatively, we can also use the includes() function:

if(arr.includes(item)) { // Returns true if the item exists, false if it doesn't

}

24. Object.entries()

This is a feature that was introduced in ES8 that allows you to convert a literal object into a key/value pair array. See the example below:

const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.entries(credits);
console.log(arr);

/** Output:
[ [ 'producer', 'John' ],
  [ 'director', 'Jane' ],
  [ 'assistant', 'Peter' ]
]
**/

25. Object.values()

This is also a new feature introduced in ES8 that performs a similar function to Object.entries(), but without the key part:

const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.values(credits);
console.log(arr);

/** Output:
[ 'John', 'Jane', 'Peter' ]
**/

26. The Spread Operator

const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

27. Decimal numbers

If you regularly work with big decimals this shorthand can be godsend, as you don’t have to type out all the zeros anymore, just replace them with the e notation. For instance, 1e8 means the addition of eight zeros after the 1 digit, it equals to 100000000.

The number after the letter e indicates the number of zeros that come after the digit(s) before e. Likewise, 16e4 is the shorthand for 160000, etc.

/* Shorthand */
var myVar = 1e8;

/* Longhand */
var myVar = 100000000;

28. Increment, decrement

The increment shorthand is made up of two + signs, it means that the value of a variable is to be incremented by one. Similarly, the decrement shorthand consists of two - signs, and it means that the variable is to be decremented by one.

These two shorthands can be used only on numeric data types.

/* Shorthand */
i++;
j--;

/* Longhand */
i=i+1;
j=j-1;

29. Add, distract, multiply, divide

There’s a shorthand for each of the four basic mathematical operations: addition, distraction, multiplication, and division. They work similarly to the increment and decrement operators, just here, you can change the value of a variable by any number (not just by one).

In the example below, the i variable is incremented by 5, j is decremented by 3, k is multiplied by 10, and l is divided by 2.

/* Shorthand */
i+=5;
j-=3;
k*=10;
l/=2;

/* Longhand */
i=i+5;
j=j-3;
k=k*10;
l=l/2;

30. Determine character position

The charAt method is one of the most frequently used string methods, it returns the character at a specified position (for instance, the 5th character of a string). There’s a simple shorthand you can use instead: you add the character position enclosed in square brackets after the string.

Pay attention that the charAt() method is zero-based. Therefore, myString[4] will return the 5th character in the string ("y" in the example).

var myString = "Happy birthday";

/* Shorthand */
myString[4];

/* Longhand */
myString.charAt(4);

31. Declare variables in bulk

If you want to create more than one variables at the same time you don’t have to type them out one by one. It’s sufficient to use the var (or let) keyword only once, then you can just list the variables you want to create, separated by a comma.

With this shorthand, you can declare both undefined variables and variables with a value.

/* Shorthand */
var i, j=5, k="Good morning", l, m=false;

/* Longhand */
var i;
var j=5;
var k="Good morning";
var l;
var m=false;

32. Declare an associative array

Declaring an array in JavaScript is a relatively simple task, by using the var myArray = ["apple", "pear", "orange"] syntax. However, declaring an associative array is a little more complicated, as here, you don’t only have to define the values but also the keys (in case of regular arrays the keys are 0, 1, 2, 3, etc.).

An associative array is a collection of key-value pairs. The longhand way is to declare the array, then add each element one by one. However, with the shorthand below, you can also declare the associative array plus all its elements at the same time.

In the example below, the myArray associative array assigns their place of birth (values) to famous people (keys).

/* Shorthand */
var myArray  = {
  "Grace Kelly": "Philadelphia",
  "Clint Eastwood": "San Francisco",
  "Humphrey Bogart": "New York City",
  "Sophia Loren": "Rome",
  "Ingrid Bergman": "Stockholm"
}

/* Longhand */
var myArray = new Array();
myArray["Grace Kelly"] = "Philadelphia";
myArray["Clint Eastwood"] = "San Francisco";
myArray["Humphrey Bogart"] = "New York City";
myArray["Sophia Loren"] = "Rome";
myArray["Ingrid Bergman"] = "Stockholm";

33. Declare an object

The shorthand for object declaration works similarly to the one for associative arrays. However here, there are not key-value pairs but property-value pairs that you need to place between the braces {}.

The only difference in the shorthand syntax is that object properties are not enclosed in quotation marks (name, placeOfBirth, age, wasJamesBond in the example below).

/* Shorthand */
var myObj = { name: "Sean Connery", placeOfBirth: "Edinburgh",
age: 86, wasJamesBond: true };

/* Longhand */
var myObj = new Object();
myObj.name = "Sean Connery";
myObj.placeOfBirth = "Edinburgh";
myObj.age = 86;
myObj.wasJamesBond = true;

34. Use the conditional operator

The conditional (ternary) operator is frequently used as the shortcut for the if-else statement. It consists of three parts:

  1. the condition
  2. what happens if the condition is true (if)
  3. what happens if the condition is false (else)

In the example below, we send a simple message (inside the message variable) to people who want to enter a club. Using the shorthand form, it’s just one line of code to run the evaluation.

var age = 17;

/* Shorthand */
var message = age >= 18 ? "Allowed" : "Denied";

/* Longhand */
if( age >= 18) {
  var message = "Allowed";
} else {
  var message = "Denied";
}

If you want to test it just copy the code into the web console (F12 in most browsers) and modify the value of the age variable a few times.

35. Check presence

It frequently happens that you need to check whether a variable is present or not. The “if presence” shorthand helps you do so with much less code.

Beware that most articles on JavaScript shorthands don’t give the proper longhand form, as the if( myVar ) notation doesn’t simply check if the variable is not false but also a handful of other things. Namely, the variable cannot be undefined, empty, null, and false.

var myVar = 99;

/* Shorthand */
if( myVar ) {
  console.log("The myVar variable is defined AND it's not empty
  AND not null AND not false.");
}

/* Longhand */
if( typeof myVar !== "undefined" && myVar !==  "" && myVar !== null
&& myVar !== 0 && myVar !== false  ) {
  console.log("The myVar variable is defined AND it's not empty
  AND not null AND not false.");
}

You can test how the “if presence” shorthand works by inserting the following code snippet into the web console and changing the value of myVar a few times.

To understand how this shorthand works, it’s worth testing it with the values of "" (empty string), false, 0, true, a non-empty string (e.g. "Hi"), a number (e.g. 99), and when the variable is undefined (simply var myVar;).

Conclusions

Suggest a JS coding technique maybe? Please add to the comments

  • Code examples (longhand and shorthand)

  • Little description when it’s useful, cautions and stuff like that

Thank you for reading!

#javascript #es6 #shorthands #developer

What is GEEK

Buddha Community

Top 35 JavaScript Shorthands for Beginners

It’s really awesome!

Sival Alethea

Sival Alethea

1624298400

Learn JavaScript - Full Course for Beginners. DO NOT MISS!!!

This complete 134-part JavaScript tutorial for beginners will teach you everything you need to know to get started with the JavaScript programming language.
⭐️Course Contents⭐️
0:00:00 Introduction
0:01:24 Running JavaScript
0:04:23 Comment Your Code
0:05:56 Declare Variables
0:06:15 Storing Values with the Assignment Operator
0:11:31 Initializing Variables with the Assignment Operator
0:11:58 Uninitialized Variables
0:12:40 Case Sensitivity in Variables
0:14:05 Add Two Numbers
0:14:34 Subtract One Number from Another
0:14:52 Multiply Two Numbers
0:15:12 Dividing Numbers
0:15:30 Increment
0:15:58 Decrement
0:16:22 Decimal Numbers
0:16:48 Multiply Two Decimals
0:17:18 Divide Decimals
0:17:33 Finding a Remainder
0:18:22 Augmented Addition
0:19:22 Augmented Subtraction
0:20:18 Augmented Multiplication
0:20:51 Augmented Division
0:21:19 Declare String Variables
0:22:01 Escaping Literal Quotes
0:23:44 Quoting Strings with Single Quotes
0:25:18 Escape Sequences
0:26:46 Plus Operator
0:27:49 Plus Equals Operator
0:29:01 Constructing Strings with Variables
0:30:14 Appending Variables to Strings
0:31:11 Length of a String
0:32:01 Bracket Notation
0:33:27 Understand String Immutability
0:34:23 Find the Nth Character
0:34:51 Find the Last Character
0:35:48 Find the Nth-to-Last Character
0:36:28 Word Blanks
0:40:44 Arrays
0:41:43 Nest Arrays
0:42:33 Access Array Data
0:43:34 Modify Array Data
0:44:48 Access Multi-Dimensional Arrays
0:46:30 push()
0:47:29 pop()
0:48:33 shift()
0:49:23 unshift()
0:50:36 Shopping List
0:51:41 Write Reusable with Functions
0:53:41 Arguments
0:55:43 Global Scope
0:59:31 Local Scope
1:00:46 Global vs Local Scope in Functions
1:02:40 Return a Value from a Function
1:03:55 Undefined Value returned
1:04:52 Assignment with a Returned Value
1:05:52 Stand in Line
1:08:41 Boolean Values
1:09:24 If Statements
1:11:51 Equality Operator
1:13:18 Strict Equality Operator
1:14:43 Comparing different values
1:15:38 Inequality Operator
1:16:20 Strict Inequality Operator
1:17:05 Greater Than Operator
1:17:39 Greater Than Or Equal To Operator
1:18:09 Less Than Operator
1:18:44 Less Than Or Equal To Operator
1:19:17 And Operator
1:20:41 Or Operator
1:21:37 Else Statements
1:22:27 Else If Statements
1:23:30 Logical Order in If Else Statements
1:24:45 Chaining If Else Statements
1:27:45 Golf Code
1:32:15 Switch Statements
1:35:46 Default Option in Switch Statements
1:37:23 Identical Options in Switch Statements
1:39:20 Replacing If Else Chains with Switch
1:41:11 Returning Boolean Values from Functions
1:42:20 Return Early Pattern for Functions
1:43:38 Counting Cards
1:49:11 Build Objects
1:50:46 Dot Notation
1:51:33 Bracket Notation
1:52:47 Variables
1:53:34 Updating Object Properties
1:54:30 Add New Properties to Object
1:55:19 Delete Properties from Object
1:55:54 Objects for Lookups
1:57:43 Testing Objects for Properties
1:59:15 Manipulating Complex Objects
2:01:00 Nested Objects
2:01:53 Nested Arrays
2:03:06 Record Collection
2:10:15 While Loops
2:11:35 For Loops
2:13:56 Odd Numbers With a For Loop
2:15:28 Count Backwards With a For Loop
2:17:08 Iterate Through an Array with a For Loop
2:19:43 Nesting For Loops
2:22:45 Do…While Loops
2:24:12 Profile Lookup
2:28:18 Random Fractions
2:28:54 Random Whole Numbers
2:30:21 Random Whole Numbers within a Range
2:31:46 parseInt Function
2:32:36 parseInt Function with a Radix
2:33:29 Ternary Operator
2:34:57 Multiple Ternary Operators
2:36:57 var vs let
2:39:02 var vs let scopes
2:41:32 const Keyword
2:43:40 Mutate an Array Declared with const
2:44:52 Prevent Object Mutation
2:47:17 Arrow Functions
2:28:24 Arrow Functions with Parameters
2:49:27 Higher Order Arrow Functions
2:53:04 Default Parameters
2:54:00 Rest Operator
2:55:31 Spread Operator
2:57:18 Destructuring Assignment: Objects
3:00:18 Destructuring Assignment: Nested Objects
3:01:55 Destructuring Assignment: Arrays
3:03:40 Destructuring Assignment with Rest Operator to Reassign Array
3:05:05 Destructuring Assignment to Pass an Object
3:06:39 Template Literals
3:10:43 Simple Fields
3:12:24 Declarative Functions
3:12:56 class Syntax
3:15:11 getters and setters
3:20:25 import vs require
3:22:33 export
3:23:40 * to Import
3:24:50 export default
3:25:26 Import a Default Export
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=PkZNo7MFNFg&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=4

🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #learn javascript #learn javascript for beginners #learn javascript - full course for beginners #javascript programming language

Lowa Alice

Lowa Alice

1624379820

JavaScript Tutorial for Beginners: Learn JavaScript in 1 Hour

Watch this JavaScript tutorial for beginners to learn JavaScript basics in one hour.
avaScript is one of the most popular programming languages in 2019. A lot of people are learning JavaScript to become front-end and/or back-end developers.

I’ve designed this JavaScript tutorial for beginners to learn JavaScript from scratch. We’ll start off by answering the frequently asked questions by beginners about JavaScript and shortly after we’ll set up our development environment and start coding.

Whether you’re a beginner and want to learn to code, or you know any programming language and just want to learn JavaScript for web development, this tutorial helps you learn JavaScript fast.

You don’t need any prior experience with JavaScript or any other programming languages. Just watch this JavaScript tutorial to the end and you’ll be writing JavaScript code in no time.

If you want to become a front-end developer, you have to learn JavaScript. It is the programming language that every front-end developer must know.

You can also use JavaScript on the back-end using Node. Node is a run-time environment for executing JavaScript code outside of a browser. With Node and Express (a popular JavaScript framework), you can build back-end of web and mobile applications.

If you’re looking for a crash course that helps you get started with JavaScript quickly, this course is for you.

⭐️TABLE OF CONTENT ⭐️

00:00 What is JavaScript
04:41 Setting Up the Development Environment
07:52 JavaScript in Browsers
11:41 Separation of Concerns
13:47 JavaScript in Node
16:11 Variables
21:49 Constants
23:35 Primitive Types
26:47 Dynamic Typing
30:06 Objects
35:22 Arrays
39:41 Functions
44:22 Types of Functions

📺 The video in this post was made by Programming with Mosh
The origin of the article: https://www.youtube.com/watch?v=W6NZfCO5SIk&list=PLTjRvDozrdlxEIuOBZkMAK5uiqp8rHUax&index=2
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#javascript #javascript tutorial #javascript tutorial for beginners #beginners

wp codevo

wp codevo

1608042336

JavaScript Shopping Cart - Javascript Project for Beginners

https://youtu.be/5B5Hn9VvrVs

#shopping cart javascript #hopping cart with javascript #javascript shopping cart tutorial for beginners #javascript cart project #javascript tutorial #shopping cart

Hire Dedicated JavaScript Developers -Hire JavaScript Developers

It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.

Does your business need an interactive website or app?

Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.

The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.

Get your business app with JavaScript

For more inquiry click here https://bit.ly/31eZyDZ

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers

Top 35 JavaScript Shorthands for Beginners

JavaScript shorthands not only speed up the coding process but also make scripts shorter, therefore lead to faster page loads

This post really is a must read for any JavaScript developer. I have written this guide to shorthand JavaScript coding techniques that I have picked up over the years. To help you understand what is going on, I have included the longhand versions to give some coding perspective.

1. The Ternary Operator

This is a great code saver when you want to write an if..else statement in just one line.

Longhand:

const x = 20;
let answer;

if (x > 10) {
    answer = "greater than 10";
} else {
    answer =  "less than 10";
}

Shorthand:

const answer = x > 10 ? "greater than 10" : "less than 10";

You can also nest your if statement like this:

const answer = x > 10 ? "greater than 10" : x < 5 ? "less than 5" : "between 5 and 10";

let someThingTrue = true
if(someThingTrue){
    console.log(“its true”)
}else{
    console.log(“its not true”)
}
****** Short Hand version below ******
let someThingTrue = true
someThingTrue ? console.log(“its true”) : console.log(“its not true”)

2. Short-circuit Evaluation Shorthand

When assigning a variable value to another variable, you may want to ensure that the source variable is not null, undefined, or empty. You can either write a long if statement with multiple conditionals, or use a short-circuit evaluation.

Longhand:

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}

Shorthand:

const variable2 = variable1  || 'new';

Don’t believe me? Test it yourself (paste the following code in es6console):

let variable1;
let variable2 = variable1  || 'bar';
console.log(variable2 === 'bar'); // prints true

variable1 = 'foo';
variable2 = variable1  || 'bar';
console.log(variable2); // prints foo

Do note that if you set variable1 to false or 0, the value bar will be assigned.

var someValueNotSureOfItsExistance = null
var expectingSomeValue = someValueNotSureOfItsExistance || “Value”

3. Declaring Variables Shorthand

It’s good practice to declare your variable assignments at the beginning of your functions. This shorthand method can save you lots of time and space when declaring multiple variables at the same time.

Longhand:

let x;
let y;
let z = 3;

Shorthand:

let x, y, z=3;

4. If Presence Shorthand

This might be trivial, but worth a mention. When doing “if checks”, assignment operators can sometimes be omitted.

Longhand:

if (likeJavaScript === true)

Shorthand:

if (likeJavaScript)

Note: these two examples are not exactly equal, as the shorthand check will pass as long as likeJavaScript is a truthy value.

Here is another example. If a is NOT equal to true, then do something.

Longhand:

let a;
if ( a !== true ) {
// do something...
}

Shorthand:

let a;
if ( !a ) {
// do something...
}

5. JavaScript For Loop Shorthand

This little tip is really useful if you want plain JavaScript and don’t want to rely on external libraries such as jQuery or lodash.

Longhand:

const fruits = ['mango', 'peach', 'banana'];
for (let i = 0; i < fruits.length; i++)

Shorthand:

for (let fruit of fruits)

If you just wanted to access the index, do:

for (let index in fruits)

This also works if you want to access keys in a literal object:

const obj = {continent: 'Africa', country: 'Kenya', city: 'Nairobi'}
for (let key in obj)
  console.log(key) // output: continent, country, city

Shorthand for Array.forEach:

function logArrayElements(element, index, array) {
  console.log("a[" + index + "] = " + element);
}
[2, 5, 9].forEach(logArrayElements);
// a[0] = 2
// a[1] = 5
// a[2] = 9

6. Short-circuit Evaluation

Instead of writing six lines of code to assign a default value if the intended parameter is null or undefined, we can simply use a short-circuit logical operator and accomplish the same thing with just one line of code.

Longhand:

let dbHost;
if (process.env.DB_HOST) {
  dbHost = process.env.DB_HOST;
} else {
  dbHost = 'localhost';
}

Shorthand:

const dbHost = process.env.DB_HOST || 'localhost';

7. Decimal Base Exponents

You may have seen this one around. It’s essentially a fancy way to write numbers without the trailing zeros. For example, 1e7 essentially means 1 followed by 7 zeros. It represents a decimal base (which JavaScript interprets as a float type) equal to 10,000,000.

Longhand:

for (let i = 0; i < 10000; i++) {}

Shorthand:

for (let i = 0; i < 1e7; i++) {}

// All the below will evaluate to true
1e0 === 1;
1e1 === 10;
1e2 === 100;
1e3 === 1000;
1e4 === 10000;
1e5 === 100000;

8. Object Property Shorthand

Defining object literals in JavaScript makes life much easier. ES6 provides an even easier way of assigning properties to objects. If the variable name is the same as the object key, you can take advantage of the shorthand notation.

Longhand:

const x = 1920, y = 1080;
const obj = { x:x, y:y };

Shorthand:

const obj = { x, y };

9. Arrow Functions Shorthand

Classical functions are easy to read and write in their plain form, but they do tend to become a bit verbose and confusing once you start nesting them in other function calls.

Longhand:

function sayHello(name) {
  console.log('Hello', name);
}

setTimeout(function() {
  console.log('Loaded')
}, 2000);

list.forEach(function(item) {
  console.log(item);
});

Shorthand:

sayHello = name => console.log('Hello', name);

setTimeout(() => console.log('Loaded'), 2000);

list.forEach(item => console.log(item));

It’s important to note that the value of this inside an arrow function is determined differently than for longhand functions, so the two examples are not strictly equivalent. See this article on arrow function syntax for more details.

10. Implicit Return Shorthand

Return is a keyword we use often to return the final result of a function. An arrow function with a single statement will implicitly return the result its evaluation (the function must omit the braces ({}) in order to omit the return keyword).

To return a multi-line statement (such as an object literal), it’s necessary to use () instead of {} to wrap your function body. This ensures the code is evaluated as a single statement.

Longhand:

function calcCircumference(diameter) {
  return Math.PI * diameter
}

Shorthand:

calcCircumference = diameter => (
  Math.PI * diameter;
)

11. Default Parameter Values

You can use the if statement to define default values for function parameters. In ES6, you can define the default values in the function declaration itself.

Longhand:

function volume(l, w, h) {
  if (w === undefined)
    w = 3;
  if (h === undefined)
    h = 4;
  return l * w * h;
}

Shorthand:

volume = (l, w = 3, h = 4 ) => (l * w * h);

volume(2) //output: 24

12. Template Literals

Aren’t you tired of using ' + ' to concatenate multiple variables into a string? Isn’t there a much easier way of doing this? If you are able to use ES6, then you are in luck. All you need to do is use is the backtick, and ${} to enclose your variables.

Longhand:

const welcome = 'You have logged in as ' + first + ' ' + last + '.'

const db = 'http://' + host + ':' + port + '/' + database;

Shorthand:

const welcome = `You have logged in as ${first} ${last}`;

const db = `http://${host}:${port}/${database}`;

13. Destructuring Assignment Shorthand

If you are working with any popular web framework, there are high chances you will be using arrays or data in the form of object literals to pass information between components and APIs. Once the data object reaches a component, you’ll need to unpack it.

Longhand:

const observable = require('mobx/observable');
const action = require('mobx/action');
const runInAction = require('mobx/runInAction');

const store = this.props.store;
const form = this.props.form;
const loading = this.props.loading;
const errors = this.props.errors;
const entity = this.props.entity;

Shorthand:

import { observable, action, runInAction } from 'mobx';

const { store, form, loading, errors, entity } = this.props;

You can even assign your own variable names:

const { store, form, loading, errors, entity:contact } = this.props;

14. Multi-line String Shorthand

If you have ever found yourself in need of writing multi-line strings in code, this is how you would write it:

Longhand:

const lorem = 'Lorem ipsum dolor sit amet, consectetur\n\t'
    + 'adipisicing elit, sed do eiusmod tempor incididunt\n\t'
    + 'ut labore et dolore magna aliqua. Ut enim ad minim\n\t'
    + 'veniam, quis nostrud exercitation ullamco laboris\n\t'
    + 'nisi ut aliquip ex ea commodo consequat. Duis aute\n\t'
    + 'irure dolor in reprehenderit in voluptate velit esse.\n\t'

But there is an easier way. Just use backticks.

Shorthand:

const lorem = `Lorem ipsum dolor sit amet, consectetur
    adipisicing elit, sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua. Ut enim ad minim
    veniam, quis nostrud exercitation ullamco laboris
    nisi ut aliquip ex ea commodo consequat. Duis aute
    irure dolor in reprehenderit in voluptate velit esse.`

15. Spread Operator Shorthand

The spread operator, introduced in ES6, has several use cases that make JavaScript code more efficient and fun to use. It can be used to replace certain array functions. The spread operator is simply a series of three dots.

Longhand

// joining arrays
const odd = [1, 3, 5];
const nums = [2 ,4 , 6].concat(odd);

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = arr.slice()

Shorthand:

// joining arrays
const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

// cloning arrays
const arr = [1, 2, 3, 4];
const arr2 = [...arr];

Unlike the concat() function, you can use the spread operator to insert an array anywhere inside another array.

const odd = [1, 3, 5 ];
const nums = [2, ...odd, 4 , 6];

You can also combine the spread operator with ES6 destructuring notation:

const { a, b, ...z } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a) // 1
console.log(b) // 2
console.log(z) // { c: 3, d: 4 }

16. Mandatory Parameter Shorthand

By default, JavaScript will set function parameters to undefined if they are not passed a value. Some other languages will throw a warning or error. To enforce parameter assignment, you can use an if statement to throw an error if undefined, or you can take advantage of the ‘Mandatory parameter shorthand’.

Longhand:

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

Shorthand:

mandatory = () => {
  throw new Error('Missing parameter!');
}

foo = (bar = mandatory()) => {
  return bar;
}

17. Array.find Shorthand

If you have ever been tasked with writing a find function in plain JavaScript, you would probably have used a for loop. In ES6, a new array function named find() was introduced.

Longhand:

const pets = [
  { type: 'Dog', name: 'Max'},
  { type: 'Cat', name: 'Karl'},
  { type: 'Dog', name: 'Tommy'},
]

function findDog(name) {
  for(let i = 0; i<pets.length; ++i) {
    if(pets[i].type === 'Dog' && pets[i].name === name) {
      return pets[i];
    }
  }
}

Shorthand:

pet = pets.find(pet => pet.type ==='Dog' && pet.name === 'Tommy');
console.log(pet); // { type: 'Dog', name: 'Tommy' }

18. Object [key] Shorthand

Did you know that Foo.bar can also be written as Foo['bar']? At first, there doesn’t seem to be a reason why you should write it like that. However, this notation gives you the building block for writing re-usable code.

Consider this simplified example of a validation function:

function validate(values) {
  if(!values.first)
    return false;
  if(!values.last)
    return false;
  return true;
}

console.log(validate({first:'Bruce',last:'Wayne'})); // true

This function does its job perfectly. However, consider a scenario where you have very many forms where you need to apply the validation but with different fields and rules. Wouldn’t it be nice to build a generic validation function that can be configured at runtime?

Shorthand:

// object validation rules
const schema = {
  first: {
    required:true
  },
  last: {
    required:true
  }
}

// universal validation function
const validate = (schema, values) => {
  for(field in schema) {
    if(schema[field].required) {
      if(!values[field]) {
        return false;
      }
    }
  }
  return true;
}

console.log(validate(schema, {first:'Bruce'})); // false
console.log(validate(schema, {first:'Bruce',last:'Wayne'})); // true

Now we have a validate function we can reuse in all forms without needing to write a custom validation function for each.

19. Double Bitwise NOT Shorthand

Bitwise operators are one of those features you learn about in beginner JavaScript tutorials and you never get to implement them anywhere. Besides, who wants to work with ones and zeroes if you are not dealing with binary?

There is, however, a very practical use case for the Double Bitwise NOT operator. You can use it as a replacement for Math.floor(). The advantage of the Double Bitwise NOT operator is that it performs the same operation much faster. You can read more about Bitwise operators here.

Longhand:

Math.floor(4.9) === 4  //true

Shorthand:

~~4.9 === 4  //true

20. Exponent Power Shorthand

Shorthand for a Math exponent power function:

Longhand:

Math.pow(2,3); // 8
Math.pow(2,2); // 4
Math.pow(4,3); // 64

Shorthand:

2**3 // 8
2**4 // 4
4**3 // 64

21. Converting a String into a Number

There are times when your code receives data that comes in String format but needs to processed in Numerical format. It’s not a big deal, we can perform a quick conversion.

Longhand:

const num1 = parseInt("100");
const num2 =  parseFloat("100.01");

Shorthand:

const num1 = +"100"; // converts to int data type
const num2 =  +"100.01"; // converts to float data type

22. Object Property Assignment

Consider the following piece of code:

let fname = { firstName : 'Black' };
let lname = { lastName : 'Panther'}

How would you merge them into one object? One way is to write a function that copies data from the second object onto the first one. Unfortunately, this might not be what you want — you may need to create an entirely new object without mutating any of the existing objects. The easiest way is to use the Object.assign function introduced in ES6:

let full_names = Object.assign(fname, lname);

You can also use the object destruction notation introduced in ES8:

let full_names = {...fname, ...lname};

There is no limit to the number of object properties you can merge. If you do have objects with identical property names, values will be overwritten in the order they were merged.

23. Bitwise IndexOf Shorthand

When performing a lookup using an array, the indexOf() function is used to retrieve the position of the item you are looking for. If the item is not found, the value -1 is returned. In JavaScript, 0 is considered ‘falsy’, while numbers greater or lesser than 0 are considered ‘truthy’. As a result, one has to write the correct code like this.

Longhand:

if(arr.indexOf(item) > -1) { // Confirm item IS found

}

if(arr.indexOf(item) === -1) { // Confirm item IS NOT found

}

Shorthand:

if(~arr.indexOf(item)) { // Confirm item IS found

}

if(!~arr.indexOf(item)) { // Confirm item IS NOT found

}

The bitwise(~) operator will return a truthy value for anything but -1. Negating it is as simple as doing !~. Alternatively, we can also use the includes() function:

if(arr.includes(item)) { // Returns true if the item exists, false if it doesn't

}

24. Object.entries()

This is a feature that was introduced in ES8 that allows you to convert a literal object into a key/value pair array. See the example below:

const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.entries(credits);
console.log(arr);

/** Output:
[ [ 'producer', 'John' ],
  [ 'director', 'Jane' ],
  [ 'assistant', 'Peter' ]
]
**/

25. Object.values()

This is also a new feature introduced in ES8 that performs a similar function to Object.entries(), but without the key part:

const credits = { producer: 'John', director: 'Jane', assistant: 'Peter' };
const arr = Object.values(credits);
console.log(arr);

/** Output:
[ 'John', 'Jane', 'Peter' ]
**/

26. The Spread Operator

const odd = [1, 3, 5 ];
const nums = [2 ,4 , 6, ...odd];
console.log(nums); // [ 2, 4, 6, 1, 3, 5 ]

27. Decimal numbers

If you regularly work with big decimals this shorthand can be godsend, as you don’t have to type out all the zeros anymore, just replace them with the e notation. For instance, 1e8 means the addition of eight zeros after the 1 digit, it equals to 100000000.

The number after the letter e indicates the number of zeros that come after the digit(s) before e. Likewise, 16e4 is the shorthand for 160000, etc.

/* Shorthand */
var myVar = 1e8;

/* Longhand */
var myVar = 100000000;

28. Increment, decrement

The increment shorthand is made up of two + signs, it means that the value of a variable is to be incremented by one. Similarly, the decrement shorthand consists of two - signs, and it means that the variable is to be decremented by one.

These two shorthands can be used only on numeric data types.

/* Shorthand */
i++;
j--;

/* Longhand */
i=i+1;
j=j-1;

29. Add, distract, multiply, divide

There’s a shorthand for each of the four basic mathematical operations: addition, distraction, multiplication, and division. They work similarly to the increment and decrement operators, just here, you can change the value of a variable by any number (not just by one).

In the example below, the i variable is incremented by 5, j is decremented by 3, k is multiplied by 10, and l is divided by 2.

/* Shorthand */
i+=5;
j-=3;
k*=10;
l/=2;

/* Longhand */
i=i+5;
j=j-3;
k=k*10;
l=l/2;

30. Determine character position

The charAt method is one of the most frequently used string methods, it returns the character at a specified position (for instance, the 5th character of a string). There’s a simple shorthand you can use instead: you add the character position enclosed in square brackets after the string.

Pay attention that the charAt() method is zero-based. Therefore, myString[4] will return the 5th character in the string ("y" in the example).

var myString = "Happy birthday";

/* Shorthand */
myString[4];

/* Longhand */
myString.charAt(4);

31. Declare variables in bulk

If you want to create more than one variables at the same time you don’t have to type them out one by one. It’s sufficient to use the var (or let) keyword only once, then you can just list the variables you want to create, separated by a comma.

With this shorthand, you can declare both undefined variables and variables with a value.

/* Shorthand */
var i, j=5, k="Good morning", l, m=false;

/* Longhand */
var i;
var j=5;
var k="Good morning";
var l;
var m=false;

32. Declare an associative array

Declaring an array in JavaScript is a relatively simple task, by using the var myArray = ["apple", "pear", "orange"] syntax. However, declaring an associative array is a little more complicated, as here, you don’t only have to define the values but also the keys (in case of regular arrays the keys are 0, 1, 2, 3, etc.).

An associative array is a collection of key-value pairs. The longhand way is to declare the array, then add each element one by one. However, with the shorthand below, you can also declare the associative array plus all its elements at the same time.

In the example below, the myArray associative array assigns their place of birth (values) to famous people (keys).

/* Shorthand */
var myArray  = {
  "Grace Kelly": "Philadelphia",
  "Clint Eastwood": "San Francisco",
  "Humphrey Bogart": "New York City",
  "Sophia Loren": "Rome",
  "Ingrid Bergman": "Stockholm"
}

/* Longhand */
var myArray = new Array();
myArray["Grace Kelly"] = "Philadelphia";
myArray["Clint Eastwood"] = "San Francisco";
myArray["Humphrey Bogart"] = "New York City";
myArray["Sophia Loren"] = "Rome";
myArray["Ingrid Bergman"] = "Stockholm";

33. Declare an object

The shorthand for object declaration works similarly to the one for associative arrays. However here, there are not key-value pairs but property-value pairs that you need to place between the braces {}.

The only difference in the shorthand syntax is that object properties are not enclosed in quotation marks (name, placeOfBirth, age, wasJamesBond in the example below).

/* Shorthand */
var myObj = { name: "Sean Connery", placeOfBirth: "Edinburgh",
age: 86, wasJamesBond: true };

/* Longhand */
var myObj = new Object();
myObj.name = "Sean Connery";
myObj.placeOfBirth = "Edinburgh";
myObj.age = 86;
myObj.wasJamesBond = true;

34. Use the conditional operator

The conditional (ternary) operator is frequently used as the shortcut for the if-else statement. It consists of three parts:

  1. the condition
  2. what happens if the condition is true (if)
  3. what happens if the condition is false (else)

In the example below, we send a simple message (inside the message variable) to people who want to enter a club. Using the shorthand form, it’s just one line of code to run the evaluation.

var age = 17;

/* Shorthand */
var message = age >= 18 ? "Allowed" : "Denied";

/* Longhand */
if( age >= 18) {
  var message = "Allowed";
} else {
  var message = "Denied";
}

If you want to test it just copy the code into the web console (F12 in most browsers) and modify the value of the age variable a few times.

35. Check presence

It frequently happens that you need to check whether a variable is present or not. The “if presence” shorthand helps you do so with much less code.

Beware that most articles on JavaScript shorthands don’t give the proper longhand form, as the if( myVar ) notation doesn’t simply check if the variable is not false but also a handful of other things. Namely, the variable cannot be undefined, empty, null, and false.

var myVar = 99;

/* Shorthand */
if( myVar ) {
  console.log("The myVar variable is defined AND it's not empty
  AND not null AND not false.");
}

/* Longhand */
if( typeof myVar !== "undefined" && myVar !==  "" && myVar !== null
&& myVar !== 0 && myVar !== false  ) {
  console.log("The myVar variable is defined AND it's not empty
  AND not null AND not false.");
}

You can test how the “if presence” shorthand works by inserting the following code snippet into the web console and changing the value of myVar a few times.

To understand how this shorthand works, it’s worth testing it with the values of "" (empty string), false, 0, true, a non-empty string (e.g. "Hi"), a number (e.g. 99), and when the variable is undefined (simply var myVar;).

Conclusions

Suggest a JS coding technique maybe? Please add to the comments

  • Code examples (longhand and shorthand)

  • Little description when it’s useful, cautions and stuff like that

Thank you for reading!

#javascript #es6 #shorthands #developer