Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Arguments

JavaScript function definitions do not specify data types for parameters. JavaScript functions do not perform type checking on the passed arguments.

JavaScript functions do not check the number of arguments received. If a function is called with missing a argument(s), the missing values are set to undefined. Extra arguments are simply ignored.

Here's a common way to check to see if a argument exists.


function myFunction(x, y)
{
    if (y === undefined)
    { y = 0;}
}

Arguments Default Values

You can set default values for function arguments. See how we never define "answer"? The function sees that it was missing and set it's default value. This is not very typical though.


let ShowSecretOfLife = (answer = "42") => { document.getElementById("demo1").innerHTML = answer;  };
ShowSecretOfLife();

Destructuring Function Arguments

Just as you can destructure arrays, you can use destructuring for functions and arguments. Take a look at the code below. You can declare just the property NAME of the object as an argument and then when you pass in the actual object, it will destructure it (some sort of reflection?) and use it's value.


// the object
let person = { Name: "Ricky Bobby", Occupation: "Race Car Driver" };

// the function (returns a string)
let GetJobOfPerson = ({Occupation}) => `Job: ${Occupation.toUpperCase()}`;

// show the property of the obj
document.getElementById("demo1").innerHTML = GetJobOfPerson(person);

And...to make it even more complicated, we can use default values for these properties just like we did for function arguments.


let car = { Color: "Red", TopSpeed: "200" };
let GetCarData = ({Color, TopSpeed, Coolness = "Very"}) =>
                    { return `Color: ${Color}, Top Speed: ${TopSpeed}, Coolness: ${Coolness}` };
document.getElementById("demo3").innerHTML = GetCarData(car);