search
HomeWeb Front-endFront-end Q&AHow to get default value in javascript

How to get default values ​​in JavaScript

When writing JavaScript code, we usually set the parameter values ​​of functions so that they can be passed to them when the function is called. However, in some cases we may want to make certain parameters have default values ​​when not explicitly set, which can make the code more concise and easier to read. This article explains how to set and use default values ​​in JavaScript.

Set default value

In the past, in order to set the default value of a function parameter, we usually needed to judge null or undefined in the function body, and then manually set a default value. As shown below:

function sayHello(name) {
    if(name === undefined) {
        name = "world";
    }
    console.log("Hello, " + name + "!");
}

sayHello(); // "Hello, world!"
sayHello("Tom"); // "Hello, Tom!"

If we have multiple parameters that need to be set to default values, this approach can easily become verbose and difficult to maintain. In ES6, we can use a more convenient way to set default values.

Use default values

In ES6, we can specify default values ​​for function parameters. This allows us to set the default value of the function more conveniently, while reducing the amount of code and improving readability. As shown below:

function sayHello(name="world") {
    console.log("Hello, " + name + "!");
}

sayHello(); // "Hello, world!"
sayHello("Tom"); // "Hello, Tom!"

In this example, we define a function sayHello and assign a default value of "world" to its parameter name. When the function is passed no parameters, it uses the default value and prints "Hello, world!". When we pass parameters to a function, it will use the value we pass, for example, when we pass Tom, it prints "Hello, Tom!".

We can also use the default values ​​​​of other parameters to set the default value. For example:

function sayHello(name="world",greeting=`Hello`) {
    console.log(`${greeting}, ${name}!`);
}

sayHello(); // "Hello, world!"
sayHello("Tom"); // "Hello, Tom!"
sayHello("Jenny", "Hi"); // "Hi, Jenny!"
sayHello(undefined, "Goodbye"); // "Goodbye, world!"

In this example, we define a function sayHello again and specify default values ​​for its parameters name and greeting. When we don't pass the greeting parameter, it will use the default value "Hello". When we pass Tom and Hi, "Hi, Tom!" is output. When we pass undefined and "Goodbye", the default value will be used and "Goodbye, world!" will be output.

Notes on default values

When using default values, you need to pay attention to the following issues:

  1. Only when the value of the parameter is undefined, Use default value. Therefore when passing false values ​​such as null, "" or 0, the default value will not be used.
function getColor(color = "blue") {
    console.log(color);
}

getColor(null); // null
getColor(""); // ""
getColor(0); // 0
  1. When using the default value, the parameter still exists, but its value is the default value. So we can still use the arguments object to access these parameters. For example:
function sayHello(name = "world") {
    console.log(`Hello, ${arguments[0]}!`);
}

sayHello("Tom"); // "Hello, Tom!"
  1. When using the default value, the parameter only applies to other parameters. If the parameter refers to the function itself or other global variables, the default value is not used. For example:
let language = "English";
function sayHello(name = "world", greeting = `Hello ${language}!`) {
    console.log(`${greeting}, ${name}!`);
}

sayHello(); // "Hello English, world!"

Conclusion

Before ES6, setting default values ​​for function parameters was cumbersome and required manual judgment of null or undefined. The emergence of ES6 makes setting default values ​​of function parameters more concise and easier to read. Setting default values ​​can make the code more concise, increase maintainability, and reduce the occurrence of errors. In addition, we also need to note that when using default values, the parameters still exist, and the default values ​​only apply to parameters that have not been set, and have nothing to do with other functions or global variables.

The above is the detailed content of How to get default value in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.