DEV Community

Henry Boisdequin
Henry Boisdequin

Posted on

Javascript Tips for Beginners

This is a list of 7 useful Javascript tips intended to improve your productivity and overall experience when using Javascript. These tips are for beginner and intermediate Javascript programmers. These tips will be arranged in no particular order. Let's move on to the tips!

1. Conditionals Without If Statements

The most common way to use conditionals in Javascript is if statements. In an if statement you can run a block of code if a specified condition is true. Also, you can add elses and else ifs for if the specified condition is false or the first specified condition is false and the next specified condition is true. This is how you would do a normal if statement in Javascript:

let x = 10;
if (x === 10) {
  // this block of code will run if x is 10
  console.log("x is 10");
} else if (x === 9) {
  // this block of code will run if x is not 10 and is 9
  console.log("x is 9");
} else {
  // this block of code will run if x is not 10 or 9
  console.log("x is not 10 or 9");
}
Enter fullscreen mode Exit fullscreen mode

To make this even better, we can make if, else statements even shorter using the ternary operator.

let x = 10;
x === 10 ? console.log("x is 10") : console.log("x is not 10");
Enter fullscreen mode Exit fullscreen mode

The statement above says if x === 10 then (specified by a question mark) do this code block (console.log("x is 10")) or (specified by a colon) do this code block (console.log("x is not 10")). You might be thinking that this is great, concise, and intuitive, but where is the else if? What if I told you that you could do an else if in a ternary operator.

let x = 10;
x === 10 ? console.log("x is 10") : (x === 9 ? console.log("x is 9") : console.log("x is not 10 or 9"));
Enter fullscreen mode Exit fullscreen mode

This way we have the if, else if, and else in a single line of code, cool! Let me show you an even shorter way in a React example!

function App() {
  const show = true;
  return show && (
    <div>
      show is true!
    <div>
  )
}
Enter fullscreen mode Exit fullscreen mode

In this case, the message "show is true!" will only render on the screen if the variable show is true. This way you can do something if the specified condition is true. This has lots of great use cases but as you can see it does have some limitations.

2. Levels of Console Messages

To print or display things in the console, most of us use the plain console.log("this will be printed in the console") but there are other ways to do it. Don't do this: console.log("ERROR:", error), there is a better way.

console.info("I am information you need to know!")
Enter fullscreen mode Exit fullscreen mode

Alt Text

console.info gives the same console.log effect but is more specific and concise code. This shows the person reading your code that you are putting information in the console.

console.warn("I am a warning!")
Enter fullscreen mode Exit fullscreen mode

Alt Text

console.warn gives the message you specified in a warning format, like above. This is a great way to put a warning in the console and to show the person reading your code that you are doing just that!

console.error("There is an error!")
Enter fullscreen mode Exit fullscreen mode

Alt Text

console.error gives the message you specified in a red error message. This is the best way to write errors into the console.

3. Spread Operator

This is the best way to merge objects and arrays. The spread syntax specifies all of the items in the object/array.

Merging an Object:

const favouriteFoods = {
  firstFood: "pizza",
  secondFood: "ice cream",
  thirdFood: "ramen"
};
const favouriteDrinks = {
  firstDrink: "ice lemon tea",
  secondDrink: "iced water",
  thirdDrink: "ginger ale"
};
// spread operator: ...objectOrArray
const myFavourtieFoodAndDrinks = {
  ...favouriteFoods,
  ...favouriteDrinks
};
Enter fullscreen mode Exit fullscreen mode

This way we can efficiently and effectively merge my favourite foods and drinks using the spread operator.

Merging an Array:

Merging an array is very similar to merging an object, but I'll show it anyway.

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = [...arr1, ...arr2];
Enter fullscreen mode Exit fullscreen mode

Using the spread operator, we can merge arr1 and arr2 to a different array (mergedArr).

4. Arrow Functions

Arrow functions are a substitute to functions declared by the keyword function. Arrow functions have become very popular, taking over the React world (most functional components use arrow functions).

Function declared by the keyword function:

function introduce(name) {
  console.log("Hello, I am " + name);
}
Enter fullscreen mode Exit fullscreen mode

Arrow Function:

const introduce = (name) => {
  console.log("Hello, I am " + name);
}
Enter fullscreen mode Exit fullscreen mode

As you can see, these are very similar but the arrow function looks slightly cleaner (personal opinion). Where arrow functions really shine are as parameters to other functions.

function add(addFunction, num1, num2) {
  console.log(addFunction(num1, num2));
}

add((num1, num2) => num1 + num2, 2, 3);
Enter fullscreen mode Exit fullscreen mode

As you can see, the arrow function is very intuitive and looks much cleaner than functions declared by the function keyword when passed as a parameter would.

5. Template Strings

Have you ever found yourself in the position where you need to print/log more than two things? Instead of doing this: console.error("Error: " + error) or console.error("Error:", error), use template strings. Template strings allow you to embed variables into strings. Take a look at some examples:

let x = 10;
console.info(`X is equal to ${x}`);
Enter fullscreen mode Exit fullscreen mode
console.info(`2 + 2 is equal to ${2 + 2}`);
Enter fullscreen mode Exit fullscreen mode

This will give us "X is equal to 10". Cool! Firstly, this string is initialized with different strings than what normal strings have (not double quotes or single quotes). Also, everything inside ${} <- that is Javascript. You can put variables in there or execute Javascript, anything you would like.

6 & 7. Different Types of Comments & Good Comments

In my opinion, one of the most important parts of your code is readability. As the name suggests, readability is the ability to read your code efficiently. Comments are one of the best ways to improve the readability of your code. Remember, all code in a comment doesn't get executed.

The most simple way to use comments:

// wow, this is a comment
Enter fullscreen mode Exit fullscreen mode

This way (single-line comments) is the most standard and is commonly used for comments which only need one line.

Bad single-line comment example:

// this code puts information into the console, more specifically puts 1+1 into the console. Also, the code is ended with a semicolon. I worked very hard on this line of code. Did I mention, that it ends with a semicolon?
console.info(1 + 1);
Enter fullscreen mode Exit fullscreen mode

This is a very bad example of a single-line comment. Good comments don't describe what the code looks like but what it does. A good test that I like to use when seeing if my comment is necessary is: if this comment wasn't there, could the person reading my comment still understand it? If the answer to that question is no, keep the comment, otherwise remove it. Let's have a look at a good comment example.

Good single-line comment example:

const myFunction = (num) => {
  // check if its a prime number
  for(let i = 2; i < num; i++)
    if(num % i === 0) return false;
  return num > 1;
}
Enter fullscreen mode Exit fullscreen mode

Since this code is not quite readable, this comment really helps to improve the readability of this code. Let's explore different types of comments.

The multiline comment is declared with this /* */.

Multiline comment example:

/* 
I am a multiline comment.

This is still a comment.

Still a comment here...
*/
Enter fullscreen mode Exit fullscreen mode

Multiline comments are great for comments which take up more than one line. Usually, multiline comments are used with the JSDoc syntax which helps to create functions more readable. JSDoc comments add the functions usage, parameters + their type, and the return value + their type.

JSDoc Comment Example:

/**
 * Returns a string introducing the name passed.
 *
 * @param {string} a name of a person
 * @return {string} a string introducing the name passed
 */
const introduce = (name) => {
  return `My name is ${name}.`
}
Enter fullscreen mode Exit fullscreen mode

As you can see, this makes your function very readable so that the person reading your code can easily understand what this function does.

Conclusion

I hope you have learnt some Javascript tips that will improve your productivity and future code. If you think that I missed out on any Javascript tips, I would love to hear them in the comments section.

Henry

Top comments (11)

Collapse
 
_garybell profile image
Gary Bell • Edited

To make this even better, we can make if, else statements even shorter using the ternary operator.

Can you explain what makes a ternary operator better than an if-else statement?

And nesting them so the else is, itself, an ternary operator is making JavaScript be like the formula bar for Excel - unreadable. If I got a code review where someone had nested ternary operators, I'd fail it on readability and maintainability grounds. If it can't be easily followed by someone new to the code base, it's pointless.

The rest of the article is pretty useful, and reminded me of a couple of things which I haven't used for a while so forgotten about.

Collapse
 
terpinmd profile image
terpinmd

By default most linting rules will fail that nested ternary. That is just a terrible pattern. I don't get this current trend with avoiding else stemtements.

Collapse
 
stefandrl profile image
Stefan Drl

I think that ternary operator is good, but! not the nested one (spaghetti code...).
I usually use it when I whant to assign a value to a variable based on a criteria.

Collapse
 
hb profile image
Henry Boisdequin

I agree with you. I just wanted to show that you could do an if, else if, and else with a ternary operator.

Thread Thread
 
_garybell profile image
Gary Bell

Thanks. It looked like you were encouraging people to do it.

I agree that ternary operators have their place, but nesting them in the real world (outside of excel or similar) is just madness

Collapse
 
aminnairi profile image
Amin

Hi Henry and thanks for your article full of interesting advices!

When it comes to printing to the console by a predicate, I like to use one console and use the ternary operator inside the method call.

const value = 10;

console.log(value !== 0 ? `Value is ${value}` : "No value");
Enter fullscreen mode Exit fullscreen mode

This shorten the code a little bit more, while still keeping the conditional rendering of those strings.

Collapse
 
hb profile image
Henry Boisdequin

Great point! This way definitely is more concise and readable.

Collapse
 
dansilcox profile image
Dan Silcox

Great tips for someone just getting started and mostly relevant to other languages not just JS!

One thing I would suggest not to use is the nested ternary operators as that really hurts readability - got to remember that as developers we should be optimising mostly for other humans to be able to read our code, not simply machines (or we would write 1s and 0s directly, right!)

Maybe another option would be to put the second ternary inside a temp variable on a separate line, e.g:
‘’’
const x = 10;
const notTen = x === 9 ?
“x is 9” :
“x is not 10”;
const logStmt = x === 10 ?
"x is 10" :
notTen;

console.log(logStmt);
‘’’
(Apologies for formatting, typing on mobile!)

Collapse
 
hb profile image
Henry Boisdequin

Great tips! I agree that the nested ternary operators are confusing but I just wanted to show that an if, else if, and else statement is possible with ternary operators. The way you did it is much cleaner.

Collapse
 
jwokiri profile image
Joe Oketch

This is excellent.

Collapse
 
hb profile image
Henry Boisdequin

Thanks!