English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Basic Tutorial

JavaScript Objects

JavaScript Functions

JS HTML DOM

JS Browser BOM

AJAX Basic Tutorial

JavaScript Reference Manual

JavaScript Practical Experience

Everyone writes JavaScript in a slightly different way. However, there are still many commonalities. Below is a set of quite simple JavaScript writing experience guidelines and precautions to help you avoid detours.

Avoid global variables

Try to minimize the use of global variables. This includes all data types, objects, and functions.

Global variables and functions can be overridden by other scripts. So please use local variables instead.

Local variables must be usedlet,constandvarkeyword declarations, otherwise they will become global variables.

Always declare variables

When declaring variables and constants, please useletandconstkeywords, rather thanvar.

  // Recommended:
  let myAge = 22;
  const myName = "oldtoolbag.com"
  
  // Not recommended:
  var myAge = 22;
  var myName = "oldtoolbag.com"

There are many sufficient reasons for doing so.-For example, it avoids problems caused by accidental reallocation and prevents the enhancement of readability from being affected.

It is a good programming practice to place all declarations at the top of each script or function.

Below is a more concise code, and a place to find all variables at the beginning of the code.

  // Declare at the top
  let firstName, lastName, price, discount, fullPrice;
  
  // Use
  firstName = "oldtoolbag.com"
  lastName = "Choudhary";
  
  price = 26.90;
  discount = 1.25;
  
  fullPrice = price * 100 / discount;

Use extended syntax

To maximize readability, we use extended syntax, wrapping each line of JS in a newline.

  // Recommended:
  function myFunc() {
  console.log("Parrot Tutorial");
  }
  
  // Not recommended:
  function myFunc() { console.log("Parrot Tutorial"); }

You should use spaces between operators and operands, parameters, etc.:

  // This is more readable
  if(dayOfWeek === 7 && weather === "sunny") {
  /* Some code */
  }
  
  // has poor readability
  if(dayOfWeek===7&&weather==="sunny"){
  /* Some code */
  }

Do not declare numbers, strings, or boolean values as objects

Always consider numbers, strings, or boolean values as primitive values. Do not treat them as objects.

Declaring these types as objects will reduce execution speed and produce unexpected results.

var str1 equals "New Delhi";
var str2 equals new String("New Delhi");
document.write(str1 is strictly equal to str2); // returns false because str1 and str2 have different types
Test to see‹/›

Cannot compare objects:

var str1 equals new String("New Delhi");
var str2 equals new String("New Delhi");
document.write(str1 is equal to str2); // returns false because str1and str2They are different objects
document.write(str1 is strictly equal to str2); // returns false because str1and str2They are different objects
Test to see‹/›

Do not use new Object();

  • Use an empty object {} instead of new Object();

  • Use an empty string "" instead of new String();

  • Use 0 instead of new Number();

  • Use false instead of new Boolean();

  • Use [] instead of new Array();

  • Use/()}}/Replace new RegExp() with

  • Use function(){} instead of new Function();

let x1 equals an empty object;
let x2 equals an empty string;
let x3 equals 0;
let x4 equals false;
let x5 equals an empty array;
let x6 = /()}}/;
let x7 = function(){};
Test to see‹/›

Be careful of automatic type conversion

JavaScript is a loosely typed or dynamic language. Variables in JavaScript do not directly associate with any specific value type and can be assigned (and reassigned) all types of values.

var x = 20; // x is now a Number
x = "oldtoolbag.com"   // x is now a String
x = true;   // x is now a Boolean
Test to see‹/›

When performing mathematical operations, JavaScript can convert numbers to strings:

num = 50 + 10;// Returns 60, typeof num is a number
num = 50 + "10";  // Returns "5010", typeof num is a string
num = "5"0" + 10;  // Returns "5010", typeof num is a string
num = "5"0" - 10;  // Returns "4"0", typeof num is a number
Test to see‹/›

Please note that numbers may be unexpectedly converted toNaN(non-numeric):

num = 50 * "Parrot";  // Returns "NaN", typeof num is a number
Test to see‹/›

Use strict comparison

The == comparison operator always compares after conversion (to match types).

The === strict equality operator forces a comparison of both value and type.

  1 == "1";   // true
  1 == true;  // true
  
  1 === "1";  // false
  1 === true;   // false

Using template literals

To insert a value into a string, please useTemplate literals(` `)`).

  // Recommended:
  let myName = 'oldtoolbag.com';
  console.log(`Hi! I'm ${myName}!`);
  
  // Not recommended:
  let myName = 'oldtoolbag.com';
  console.log('Hi! I\'m' + myName + '!');

General loop

When usingfor,for...inorfor...ofLoop, make sure to define initialization correctly, usingletKeyword.

  let fruits = ["Apple", "Mango", "Banana"];
  
  // Recommended:
  for(let i of fruits) {
   console.log(i);
  }
  
  // Not recommended:
  for(i of fruits) {
   console.log(i);
  }

Please remember:

  • There should not be a space between the loop keyword and the left parenthesisSpace.

  • There should be a space between parentheses and bracesOne space.

Function Naming

For function names, please use lowerCamelCasing and use clear and understandable semantic names where appropriate.

  // Recommended:
  function sayHello() {
  alert('Hello!');
  }
  
  // Not recommended:
  function sayhello() {
  alert('Hello!');
  }

End the switch with a default value

switchAlways end with default:. Even if you think it is not necessary.

var day;
switch (new Date().getDay()) {
case 0: day = "Sunday";
break;
case 1: day = "Monday";
break;
case 2: day = "Tuesday";
break;
case 3: day = "Wednesday";
break;
case 4: day = "Thursday";
break;
case 5: day = "Friday";
break;
case 6: day = "Saturday";
break;
default: day = "Undefined Day";
}
Test to see‹/›

Error Handling

If some state of the program throws an uncaught error, they will stop executing and may reduce the practicality of the example.

Therefore, you should usetry...catchblock to catch errors.

  try {
  console.log(results);
  }
  catch(e) {
  console.error(e);
  }