SoFunction
Updated on 2025-02-28

The parsing and execution order of javascript is different in each browser

Introduction

Javascript is an interpreted language, and its execution is top-down. However, each browser has slight differences in its understanding of [top-down], and the upstream and downstream of the code, that is, the program flow, is crucial for the correct operation of the program. So it is necessary to understand the execution order of js in depth. To this end, I designed the following eight experiments to obtain the most accurate results.

experiment

<script type="text/javascript">
//Experiment 1:function t(a)
{
alert("[t(a)]a:" + a);
}
function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
t(1);
//result://[t(a, b)]a:1, b:undefined
//Experiment 2:function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
function t(a)
{
alert("[t(a)]a:" + a);
}
t(1);
//result://[t(a)]a:1
//Experiment 3:function t(a)
{
alert("[t(a)]a:" + a);
}
function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
t(1, 2);
//result://[t(a, b)]a:1, b:2
//Experiment 4:function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
function t(a)
{
alert("[t(a)]a:" + a);
}
t(1, 2);
//result://[t(a)]a:1
//Experiment 5function t(a)
{
alert("[t(a)]a:" + a);
}
t(1);
function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
//result://[t(a, b)]a:1, b:undefined
//Experiment 6function t(a)
{
alert("[t(a)]a:" + a);
}
t(1, 2);
function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
//result://[t(a, b)]a:1, b:2
//Experiment 7function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
t(1);
function t(a)
{
alert("[t(a)]a:" + a);
}
//result://[t(a)]a:1
//Experiment 8function t(a, b)
{
alert("[t(a, b)]a:" + a + ", b:" + b);
}
t(1, 2);
function t(a)
{
alert("[t(a)]a:" + a);
}
//result://[t(a)]a:1
</script>

postscript

When defining a javascript function, the function name is the identifier of the function object, and the number of parameters is only the attribute of the function. It is not possible to implement overloading by defining functions with different number of parameters.
When calling a function, js finds the corresponding function object through the function name, and then matches the parameters of the function definition and the expression parameter list in order. The extra parameters are discarded, and the insufficient parameters are processed as undefined, and then the function code is executed.

Therefore, when defining a function, the required parameters are usually placed at the front of the parameter list and the optional parameters are placed after the required parameters.

Things to note

1. The results of the above eight experiments were obtained by running through 360 browser (version/kernel: 6.3.1.142/21.0.1180.89) and Firefox browser (version: 27.0.1).
2. The above eight experiments are independent of each other. Please run them separately to get the correct results.