Rectangle 27 618

Inside a function, the bytecode is

2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_FAST               0 (i)

  3          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               0 (None)
             26 RETURN_VALUE

At top level, the bytecode is

1           0 SETUP_LOOP              20 (to 23)
              3 LOAD_NAME                0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_NAME               1 (i)

  2          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               2 (None)
             26 RETURN_VALUE

The difference is that STORE_FAST is faster (!) than STORE_NAME. This is because in a function, i is a local but at toplevel it is a global.

To examine bytecode, use the dis module. I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin.

Confirmed by experiment. Inserting global i into the main function makes the running times equivalent.

This answers the question without answering the question :) In the case of local function variables, CPython actually stores these in a tuple (which is mutable from the C code) until a dictionary is requested (e.g. via locals(), or inspect.getframe() etc.). Looking up an array element by a constant integer is much faster than searching a dict.

It is the same with C/C++ also, using global variables causes significant slowdown

@gkimsey I agree. Just wanted to share two things i) This behaviour is noted in other programming languages ii) The causal agent is more the architectural side and not the language itself in true sense

performance - Why does Python code run faster in a function? - Stack O...

python performance profiling benchmarking cpython
Rectangle 27 618

Inside a function, the bytecode is

2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_FAST               0 (i)

  3          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               0 (None)
             26 RETURN_VALUE

At top level, the bytecode is

1           0 SETUP_LOOP              20 (to 23)
              3 LOAD_NAME                0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_NAME               1 (i)

  2          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               2 (None)
             26 RETURN_VALUE

The difference is that STORE_FAST is faster (!) than STORE_NAME. This is because in a function, i is a local but at toplevel it is a global.

To examine bytecode, use the dis module. I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin.

Confirmed by experiment. Inserting global i into the main function makes the running times equivalent.

This answers the question without answering the question :) In the case of local function variables, CPython actually stores these in a tuple (which is mutable from the C code) until a dictionary is requested (e.g. via locals(), or inspect.getframe() etc.). Looking up an array element by a constant integer is much faster than searching a dict.

It is the same with C/C++ also, using global variables causes significant slowdown

@gkimsey I agree. Just wanted to share two things i) This behaviour is noted in other programming languages ii) The causal agent is more the architectural side and not the language itself in true sense

performance - Why does Python code run faster in a function? - Stack O...

python performance profiling benchmarking cpython
Rectangle 27 618

Inside a function, the bytecode is

2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_FAST               0 (i)

  3          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               0 (None)
             26 RETURN_VALUE

At top level, the bytecode is

1           0 SETUP_LOOP              20 (to 23)
              3 LOAD_NAME                0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_NAME               1 (i)

  2          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               2 (None)
             26 RETURN_VALUE

The difference is that STORE_FAST is faster (!) than STORE_NAME. This is because in a function, i is a local but at toplevel it is a global.

To examine bytecode, use the dis module. I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin.

Confirmed by experiment. Inserting global i into the main function makes the running times equivalent.

This answers the question without answering the question :) In the case of local function variables, CPython actually stores these in a tuple (which is mutable from the C code) until a dictionary is requested (e.g. via locals(), or inspect.getframe() etc.). Looking up an array element by a constant integer is much faster than searching a dict.

It is the same with C/C++ also, using global variables causes significant slowdown

@gkimsey I agree. Just wanted to share two things i) This behaviour is noted in other programming languages ii) The causal agent is more the architectural side and not the language itself in true sense

performance - Why does Python code run faster in a function? - Stack O...

python performance profiling benchmarking cpython
Rectangle 27 618

Inside a function, the bytecode is

2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_FAST               0 (i)

  3          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               0 (None)
             26 RETURN_VALUE

At top level, the bytecode is

1           0 SETUP_LOOP              20 (to 23)
              3 LOAD_NAME                0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_NAME               1 (i)

  2          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               2 (None)
             26 RETURN_VALUE

The difference is that STORE_FAST is faster (!) than STORE_NAME. This is because in a function, i is a local but at toplevel it is a global.

To examine bytecode, use the dis module. I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin.

Confirmed by experiment. Inserting global i into the main function makes the running times equivalent.

This answers the question without answering the question :) In the case of local function variables, CPython actually stores these in a tuple (which is mutable from the C code) until a dictionary is requested (e.g. via locals(), or inspect.getframe() etc.). Looking up an array element by a constant integer is much faster than searching a dict.

It is the same with C/C++ also, using global variables causes significant slowdown

@gkimsey I agree. Just wanted to share two things i) This behaviour is noted in other programming languages ii) The causal agent is more the architectural side and not the language itself in true sense

performance - Why does Python code run faster in a function? - Stack O...

python performance profiling benchmarking cpython
Rectangle 27 618

Inside a function, the bytecode is

2           0 SETUP_LOOP              20 (to 23)
              3 LOAD_GLOBAL              0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_FAST               0 (i)

  3          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               0 (None)
             26 RETURN_VALUE

At top level, the bytecode is

1           0 SETUP_LOOP              20 (to 23)
              3 LOAD_NAME                0 (xrange)
              6 LOAD_CONST               3 (100000000)
              9 CALL_FUNCTION            1
             12 GET_ITER            
        >>   13 FOR_ITER                 6 (to 22)
             16 STORE_NAME               1 (i)

  2          19 JUMP_ABSOLUTE           13
        >>   22 POP_BLOCK           
        >>   23 LOAD_CONST               2 (None)
             26 RETURN_VALUE

The difference is that STORE_FAST is faster (!) than STORE_NAME. This is because in a function, i is a local but at toplevel it is a global.

To examine bytecode, use the dis module. I was able to disassemble the function directly, but to disassemble the toplevel code I had to use the compile builtin.

Confirmed by experiment. Inserting global i into the main function makes the running times equivalent.

This answers the question without answering the question :) In the case of local function variables, CPython actually stores these in a tuple (which is mutable from the C code) until a dictionary is requested (e.g. via locals(), or inspect.getframe() etc.). Looking up an array element by a constant integer is much faster than searching a dict.

It is the same with C/C++ also, using global variables causes significant slowdown

@gkimsey I agree. Just wanted to share two things i) This behaviour is noted in other programming languages ii) The causal agent is more the architectural side and not the language itself in true sense

performance - Why does Python code run faster in a function? - Stack O...

python performance profiling benchmarking cpython
Rectangle 27 24

At the top level (outside a function)

Variables declared using the let keyword are block-scoped, which means that they are available only in the block in which they were declared.

At the top level, variables declared using let don't create properties on the global object.

var globalVariable = 42;
let blockScopedVariable = 43;

console.log(globalVariable); // 42
console.log(blockScopedVariable); // 43

console.log(this.globalVariable); // 42
console.log(this.blockScopedVariable); // undefined

Inside a funciton (but outside a block), let has the same scope as var.

(() => {
  var functionScopedVariable = 42;
  let blockScopedVariable = 43;

  console.log(functionScopedVariable); // 42
  console.log(blockScopedVariable); // 43
})();

console.log(functionScopedVariable); // ReferenceError: functionScopedVariable is not defined
console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined

Variables declared using let inside a block can't be accessed outside that block.

{
  var globalVariable = 42;
  let blockScopedVariable = 43;
  console.log(globalVariable); // 42
  console.log(blockScopedVariable); // 43
}

console.log(globalVariable); // 42
console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined

Variables declared with let in loops can be referenced only inside that loop.

for (var i = 0; i < 3; i++) {
  var j = i * 2;
}
console.log(i); // 3
console.log(j); // 4

for (let k = 0; k < 3; k++) {
  let l = k * 2;
}
console.log(typeof k); // undefined
console.log(typeof l); // undefined
// Trying to do console.log(k) or console.log(l) here would throw a ReferenceError.

If you use let instead of var in a loop, with each iteration you get a new variable. That means that you can safely use a closure inside a loop.

// Logs 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

// Logs 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j), 0);
}

Because of the temporal dead zone, variables declared using let can't be accessed before they are declared. Attempting to do so throws an error.

console.log(noTDZ); // undefined
var noTDZ = 43;
console.log(hasTDZ); // ReferenceError: hasTDZ is not defined
let hasTDZ = 42;

You can't declare the same variable multiple times using let. You also can't declare a variable using let with the same identifier as another variable which was declared using var.

var a;
var a; // Works fine.

let b;
let b; // SyntaxError: Identifier 'b' has already been declared

var c;
let c; // SyntaxError: Identifier 'c' has already been declared

const is quite similar to letit's block-scoped and has TDZ. There are, however, two things which are different.

const
const a = 42;
a = 43; // TypeError: Assignment to constant variable.

Note that it doesn't mean that the value is immutable. Its properties still can be changed.

const obj = {};
obj.a = 42;
console.log(obj.a); // 42

If you want to have an immutable object, you should use Object.freeze().

You always must specify a value when declaring a variable using const.

const a; // SyntaxError: Missing initializer in const declaration

javascript - What's the difference between using "let" and "var" to de...

javascript scope ecmascript-6 var let
Rectangle 27 24

At the top level (outside a function)

Variables declared using the let keyword are block-scoped, which means that they are available only in the block in which they were declared.

At the top level, variables declared using let don't create properties on the global object.

var globalVariable = 42;
let blockScopedVariable = 43;

console.log(globalVariable); // 42
console.log(blockScopedVariable); // 43

console.log(this.globalVariable); // 42
console.log(this.blockScopedVariable); // undefined

Inside a funciton (but outside a block), let has the same scope as var.

(() => {
  var functionScopedVariable = 42;
  let blockScopedVariable = 43;

  console.log(functionScopedVariable); // 42
  console.log(blockScopedVariable); // 43
})();

console.log(functionScopedVariable); // ReferenceError: functionScopedVariable is not defined
console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined

Variables declared using let inside a block can't be accessed outside that block.

{
  var globalVariable = 42;
  let blockScopedVariable = 43;
  console.log(globalVariable); // 42
  console.log(blockScopedVariable); // 43
}

console.log(globalVariable); // 42
console.log(blockScopedVariable); // ReferenceError: blockScopedVariable is not defined

Variables declared with let in loops can be referenced only inside that loop.

for (var i = 0; i < 3; i++) {
  var j = i * 2;
}
console.log(i); // 3
console.log(j); // 4

for (let k = 0; k < 3; k++) {
  let l = k * 2;
}
console.log(typeof k); // undefined
console.log(typeof l); // undefined
// Trying to do console.log(k) or console.log(l) here would throw a ReferenceError.

If you use let instead of var in a loop, with each iteration you get a new variable. That means that you can safely use a closure inside a loop.

// Logs 3 thrice, not what we meant.
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

// Logs 0, 1 and 2, as expected.
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j), 0);
}

Because of the temporal dead zone, variables declared using let can't be accessed before they are declared. Attempting to do so throws an error.

console.log(noTDZ); // undefined
var noTDZ = 43;
console.log(hasTDZ); // ReferenceError: hasTDZ is not defined
let hasTDZ = 42;

You can't declare the same variable multiple times using let. You also can't declare a variable using let with the same identifier as another variable which was declared using var.

var a;
var a; // Works fine.

let b;
let b; // SyntaxError: Identifier 'b' has already been declared

var c;
let c; // SyntaxError: Identifier 'c' has already been declared

const is quite similar to letit's block-scoped and has TDZ. There are, however, two things which are different.

const
const a = 42;
a = 43; // TypeError: Assignment to constant variable.

Note that it doesn't mean that the value is immutable. Its properties still can be changed.

const obj = {};
obj.a = 42;
console.log(obj.a); // 42

If you want to have an immutable object, you should use Object.freeze().

You always must specify a value when declaring a variable using const.

const a; // SyntaxError: Missing initializer in const declaration

javascript - What's the difference between using "let" and "var" to de...

javascript scope ecmascript-6 var let
Rectangle 27 1120

  • A static variable inside a function keeps its value between invocations.
  • A static global variable or a function is "seen" only in the file it's declared in

(1) is the more foreign topic if you're a newbie, so here's an example:

#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60

This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

Being a little pedantic, it's compilation unit, not file.

Pax, the OP doesn't know about static, so you suggest plunging him into the difference between compilation units and files ? :-)

Wait, what's a compilation unit?

A compilation unit is a single file the compiler sees. Your .c file may include other .c files, but after the preprocessor sorting out the includes, the compiler eventually sees just a single "compilation unit".

@robUK: the compiler doesn't even know about the .h files - these are combined into the .c files in the pre-processor. So yes you can say that the .c file, with all the headers included into it, are a single compilation unit.

syntax - What does "static" mean in C? - Stack Overflow

c syntax static
Rectangle 27 1090

  • A static variable inside a function keeps its value between invocations.
  • A static global variable or a function is "seen" only in the file it's declared in

(1) is the more foreign topic if you're a newbie, so here's an example:

#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60

This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

Being a little pedantic, it's compilation unit, not file.

Pax, the OP doesn't know about static, so you suggest plunging him into the difference between compilation units and files ? :-)

Wait, what's a compilation unit?

A compilation unit is a single file the compiler sees. Your .c file may include other .c files, but after the preprocessor sorting out the includes, the compiler eventually sees just a single "compilation unit".

@robUK: the compiler doesn't even know about the .h files - these are combined into the .c files in the pre-processor. So yes you can say that the .c file, with all the headers included into it, are a single compilation unit.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

syntax - What does "static" mean in C? - Stack Overflow

c syntax static
Rectangle 27 1082

  • A static variable inside a function keeps its value between invocations.
  • A static global variable or a function is "seen" only in the file it's declared in

(1) is the more foreign topic if you're a newbie, so here's an example:

#include <stdio.h>

void foo()
{
    int a = 10;
    static int sa = 10;

    a += 5;
    sa += 5;

    printf("a = %d, sa = %d\n", a, sa);
}


int main()
{
    int i;

    for (i = 0; i < 10; ++i)
        foo();
}
a = 15, sa = 15
a = 15, sa = 20
a = 15, sa = 25
a = 15, sa = 30
a = 15, sa = 35
a = 15, sa = 40
a = 15, sa = 45
a = 15, sa = 50
a = 15, sa = 55
a = 15, sa = 60

This is useful for cases where a function needs to keep some state between invocations, and you don't want to use global variables. Beware, however, this feature should be used very sparingly - it makes your code not thread-safe and harder to understand.

(2) Is used widely as an "access control" feature. If you have a .c file implementing some functionality, it usually exposes only a few "public" functions to users. The rest of its functions should be made static, so that the user won't be able to access them. This is encapsulation, a good practice.

In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack.

In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant.

Being a little pedantic, it's compilation unit, not file.

Pax, the OP doesn't know about static, so you suggest plunging him into the difference between compilation units and files ? :-)

Wait, what's a compilation unit?

A compilation unit is a single file the compiler sees. Your .c file may include other .c files, but after the preprocessor sorting out the includes, the compiler eventually sees just a single "compilation unit".

@robUK: the compiler doesn't even know about the .h files - these are combined into the .c files in the pre-processor. So yes you can say that the .c file, with all the headers included into it, are a single compilation unit.

c - What does "static" mean? - Stack Overflow

c syntax static
Rectangle 27 23

Checking / Switching inside the function is not OVERLOADING.

The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

All suggested implementations are great, but truth to be told, there is no native implementation for JavaScript.

What is the best way to FAKE function overloading in JavaScript?

If a person ask a question that is wrong, you can't just answer it, we are here to clarify for less educated people on the subject, so, faking something that the platform doesn't support it is very stupid IMHO...

But the fact that someone asked how to "fake it" already implies that they know true overloading is not possible. Answers should provide solutions, not clarifications.

My point is: If you're not answering his question, don't post an answer. This is a worthy comment, but it should not have been an answer.

Function overloading in Javascript - Best practices - Stack Overflow

javascript method-overloading
Rectangle 27 22

Checking / Switching inside the function is not OVERLOADING.

The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

All suggested implementations are great, but truth to be told, there is no native implementation for JavaScript.

What is the best way to FAKE function overloading in JavaScript?

If a person ask a question that is wrong, you can't just answer it, we are here to clarify for less educated people on the subject, so, faking something that the platform doesn't support it is very stupid IMHO...

But the fact that someone asked how to "fake it" already implies that they know true overloading is not possible. Answers should provide solutions, not clarifications.

My point is: If you're not answering his question, don't post an answer. This is a worthy comment, but it should not have been an answer.

Function overloading in Javascript - Best practices - Stack Overflow

javascript method-overloading
Rectangle 27 22

Checking / Switching inside the function is not OVERLOADING.

The concept of overloading: In some programming languages, function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

All suggested implementations are great, but truth to be told, there is no native implementation for JavaScript.

What is the best way to FAKE function overloading in JavaScript?

If a person ask a question that is wrong, you can't just answer it, we are here to clarify for less educated people on the subject, so, faking something that the platform doesn't support it is very stupid IMHO...

But the fact that someone asked how to "fake it" already implies that they know true overloading is not possible. Answers should provide solutions, not clarifications.

My point is: If you're not answering his question, don't post an answer. This is a worthy comment, but it should not have been an answer.

Function overloading in Javascript - Best practices - Stack Overflow

javascript method-overloading
Rectangle 27 185

There are two ways to get the event object from inside a function:

  • The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  • The window.event object in Internet Explorer (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

From an inline listener, you can pass the event object like: onclick="foo(event)", then in the function function foo(event){/* do stuff with event */}. This works in both IE and W3C event models.

javascript - How to stop event propagation with inline onclick attribu...

javascript html events dom
Rectangle 27 185

There are two ways to get the event object from inside a function:

There are two ways to get the event object from inside a function:

  • The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  • The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  • The window.event object in Internet Explorer (<=8)
  • The window.event object in Internet Explorer (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}
function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"
onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

From an inline listener, you can pass the event object like: onclick="foo(event)", then in the function function foo(event){/* do stuff with event */}. This works in both IE and W3C event models.

From an inline listener, you can pass the event object like: onclick="foo(event)", then in the function function foo(event){/* do stuff with event */}. This works in both IE and W3C event models.

javascript - How to stop event propagation with inline onclick attribu...

javascript html events dom
Rectangle 27 184

There are two ways to get the event object from inside a function:

  • The first argument, in a W3C-compliant browser (Chrome, Firefox, Safari, IE9+)
  • The window.event object in Internet Explorer (<=8)

If you need to support legacy browsers that don't follow the W3C recommendations, generally inside a function you would use something like the following:

function(e) {
  var event = e || window.event;
  [...];
}

which would check first one, and then the other and store whichever was found inside the event variable. However in an inline event handler there isn't an e object to use. In that case you have to take advantage of the arguments collection which is always available and refers to the complete set of arguments passed to a function:

onclick="var event = arguments[0] || window.event; [...]"

However, generally speaking you should be avoiding inline event handlers if you need to to anything complicated like stopping propagation. Writing your event handlers separately and the attaching them to elements is a much better idea in the medium and long term, both for readability and maintainability.

From an inline listener, you can pass the event object like: onclick="foo(event)", then in the function function foo(event){/* do stuff with event */}. This works in both IE and W3C event models.

javascript - How to stop event propagation with inline onclick attribu...

javascript html events dom
Rectangle 27 77

class MyClass
{
    const MYCONSTANT = 'constant value';

    function showConstant() {
        echo  self::MYCONSTANT. "\n";
    }
}

echo MyClass::MYCONSTANT. "\n";

$classname = "MyClass";
echo $classname::MYCONSTANT. "\n"; // As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::MYCONSTANT."\n"; // As of PHP 5.3.0

In this case echoing MYCONSTANT by itself would raise a notice about an undefined constant and output the constant name converted to a string: "MYCONSTANT".

class MyClass
{
    private static $staticVariable = null;

    public static function showStaticVariable($value = null)
    {
        if ((is_null(self::$staticVariable) === true) && (isset($value) === true))
        {
            self::$staticVariable = $value;
        }

        return self::$staticVariable;
    }
}

MyClass::showStaticVariable(); // null
MyClass::showStaticVariable('constant value'); // "constant value"
MyClass::showStaticVariable('other constant value?'); // "constant value"
MyClass::showStaticVariable(); // "constant value"

but it doesn't work to define it inside a function of the class :(

(is_null(self::$staticVariable) === true) && (isset($value) === true)
self::$staticVariable === null && $value !== null
$value
isset
=== true

@deceze: Please, not again...

PHP - define constant inside a class - Stack Overflow

php class constants
Rectangle 27 528

Think of it like you're just calling JavaScript functions. You can't put a for loop inside a function call:

return tbody(
    for (var i = 0; i < numrows; i++) {
        ObjectRow()
    } 
)

But you can make an array, and then pass that in:

var rows = [];
for (var i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);

You can use basically the same structure when working with JSX:

var rows = [];
for (var i=0; i < numrows; i++) {
    rows.push(<ObjectRow />);
}
return <tbody>{rows}</tbody>;

Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.

It's possible the compiler has changed, as this example doesn't seem to compile in the jsx compiler, but using map as in FakeRainBrigand's answer below does seem to compile correctly.

I can promise that the last example still compiles correctly on the latest JSX compiler.

This works well. FakeRainBrigand's answer works for simple array iteration, but this answer is a must for scenarios where you can't use map (e.g. you don't have a collection stored in a variable).

Note that if ObjectRow has any attributes, don't put the attribute values in quotations or they won't get interpolated; so do <ObjectRow name={i}/> instead of <ObjectRow name="{i}"/>.

React needs to update dom efficiently, in this case, the parent should assign a key to each childern. REF: facebook.github.io/react/docs/

javascript - Loop inside React JSX - Stack Overflow

javascript reactjs
Rectangle 27 40

if you are inside a function, missing() is what you want.

exchequer = function(x) {
    if(missing(x)){
        message("x is missing :-(")
    }
}

exchequer()
x is missing :-(

How to check if object (variable) is defined in R? - Stack Overflow

r
Rectangle 27 38

You call both event listeners using .on() then use a if inside the function:

$(function(){
  $('#searchButton').on('keypress click', function(e){
    var search = $('#usersSearch').val();
    if (e.which === 13 || e.type === 'click') {
      $.post('../searchusers.php', {search: search}, function (response) {
        $('#userSearchResultsTable').html(response);
      });
    }
  });
});

Why does this answer does not get more votes? I mean this is lesser code blocks (like not to add another event to trigger a click). Any downside of this?

You need to capture the keypress from the search field, and the click from the search button. Those are two separate DOM entities, and so this code won't work.

jquery - Trigger an event on `click` and `enter` - Stack Overflow

jquery jquery-selectors