I am curious why this won't alert my greeting. The code:
function myNameWelcome(userName, thought) {
var greeting = "Welcome pardner, so your're name is " + userName + ". " + thought;
return greeting;
}
myNameWelcome("Peter", "Shine on you crazy diamond.");
alert(greeting);
greeting is out of scope. It was defined inside the function so it's not available at the scope you're calling alert(greeting);. Fixing this is easy:
var greeting;
function myNameWelcome(userName, thought) {
greeting = "Welcome pardner, so your're name is " + userName + ". " + thought;
}
myNameWelcome("Peter", "Shine on you crazy diamond.");
alert(greeting);
or even better:
function myNameWelcome(userName, thought) {
return "Welcome pardner, so your're name is " + userName + ". " + thought;
}
var greeting = myNameWelcome("Peter", "Shine on you crazy diamond.");
alert(greeting);
Your return value isn't being assigned to anything outside of the function.
Because greeting is a local variable only accessible within myNameWelcome. It does not exist outside of the function.
See What is the scope of variables in JavaScript? to learn more about variable scope.
Related
I have been recently learning JavaScript and came across this piece of code.
function sayIntro(name,age){
var address = "TX";
return function(name,age,address){
console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};
}
sayIntro("john",27)();
As per my understanding, the results are undefined because
within the scope of returning function previous variables are not available. Still how do I get the output as bellow?
I am john
I am 27
from TX
The parameters from the inner function shadows the outer function parameters and the variable. You can just access the variables inside the inner function, because when it tries to find a variable, it goes from its scope, if not found goes to the outer scope, in this case the outer function's scope and finds them.
But if you declare parameters in the inner function, they are founded and because you does not pass a value for them, their values are undefined. So you get undefined.
Or remove them from the inner function
return function() {
console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};
or just remove the address and call the inner function and pass to it the parameters.
return function(name, age) {
console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};
...
sayIntro()("john",27);
Example
function sayIntro(name,age){
var address = "TX";
return function(){
console.log("I am "+ name + " \nI am "+ age + " \nfrom "+address);
};
}
sayIntro("john",27)();
I have this code when i run it displays undefined. However we can access global property with this keyword.
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// "this" inside this function will have the value of the window object
// because the showFullName () function is defined in the global scope, just like the firstName and lastName
alert (this.firstName + " " + this.lastName);
}
showFullName ();
This works if executed properly (replaced alert with console.log for easier examples)
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// "this" inside this function will have the value of the window object
console.log("this and window are the same thing", this === window);
// because the showFullName () function is defined in the global scope, just like the firstName and lastName
console.log(this.firstName + " " + this.lastName);
}
showFullName();
If this is placed in functional scope it will not work, however - presumably JS Fiddle does something like that
(function() {
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// "this" inside this function will still have the value of the window object
console.log("this and window are the same thing", this === window);
// however firstName and lastName are not goint to be attached to it because they are in functional scope
console.log("the names are still reachable", firstName, lastName)
//but not attached to the window object (which "this" points to)
console.log(this.firstName + " " + this.lastName);
}
showFullName();
})();
Do note that with if you have strict mode enabled then this will be undefined instead of window and the code will produce an error
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
"use strict";
// "this" inside this function will now have the value "undefined"
console.log("'this' is actually 'undefined'", this);
console.log("the actual value 'undefined', not a string", typeof this);
// the following line will throw a TypeError because it's trying to get a property from "undefined"
console.log(this.firstName + " " + this.lastName);
}
showFullName();
Normaly use window keyword instead. this is independent on place where was funciton declared but is dependent on place where was (and how) called.
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
alert (window.firstName + " " + window.lastName);
}
showFullName();
So i came to know that, when we use strict mode, this keyword holds the value of undefined in global functions.
In strict mode, however, the value of this remains at whatever it was set to when entering the execution context, so, in the following case, this will default to undefined:
function f2(){
"use strict"; // see strict mode
return this;
}
f2() === undefined;
So, in strict mode, if this was not defined by the execution context, it remains undefined.I have taken this code snippet from MDN.
So in my case value is not appearing in fiddle.But it would be reason which is pointed out by #vlaz. Thanks #vlaz
I am not seeing the issue here. I am new at JavaScript. I have researched variable scope and this looks correct to me. The issue is the variable, useAge, in the legalAge function is undefined. I have it declared before the function and passing it as a parameter to the function.
"use strict";
function person(){
alert("person function 1");
var personName = prompt("Enter a name:", "enter name here");
var personAge = parseInt(prompt("Enter " + personName + "'s current age:", "enter age here"));
var votingStatus = legalAge();
var statusMessage = (votingStatus == true) ? "old enough" : "not old enough";
document.writeln("<b>" + personName + " is " + personAge + " years old " + statusMessage + "</b><br />");
return personAge;
}
var useAge = person();
alert("useAge: " + useAge);
alert("outside function");
function legalAge(useAge) {
alert("legalVoting function 2");
var canVote = (useAge >= 18) ? true : false;
alert("Can Vote: " + canVote);
alert("age: " + useAge);
return canVote;
}
person();
The problem is that you haven't passed personAge into the legalAge() function. You need:
var votingStatus = legalAge(personAge);
Otherwise useAge in legalAge() is undefined and you'll get errors using it.
Couple things to note here:
var useAge = person()
The above line will assign the return value from person() to useAge sure enough...
function legalAge(useAge) {
....
}
The above function has a parameter called useAge which is local to the function, and must be passed as an argument when calling the function. I.E. legalAge(10). This would be fine and dandy, except...
function person() {
....
var votingStatus = legalAge();
....
}
the person() function is defined to call legalAge() with no parameters. In doing so, legalAge executes and does not have a value for its parameter.
Also, the useAge parameter is different from the global useAge variable.
Hope this helps!
i just started with learning Javascript and Jasmine and stumbled about the following error Message when i run the test: "ReferenceError: greet is not defined"
// greetSpec.js
describe('greeter', function() {
return it('should greet with message and name', function() {
var result;
result = greet('Hello', 'John Doe');
return expect(result).toBe('Hello, John Doe!');
});
});
// greet.js
var greet;
greet = function(message, person) {
var greeting;
return greeting = "" + message + ", " + person + "!";
};
The function is defined before the declaration of greet. Think of the file being scanned from top-to-bottom. By the time it gets to the describe call, the variable greet does not exist, hence the error. Try putting the greet function definition above the call.
Turns out, as Lennier put it, that there was "a conflict between some of the coffeescript generated files." Glad I could help though.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: var functionName = function() {} vs function functionName() {}
What is the difference between a function expression vs declaration in Javascript?
I am attempting to understand the "best practices" of javascript.
This code is from jqfundementals.com
// create a function that will greet a person,
// and assign the function to the `greet` variable
var greet = function( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
greet( 'Jory', 'Welcome to JavaScript' );
greet( 'Rebecca', 'Thanks for joining us' );
Why should I assign the function to the greet variable?
My first impulse would be to write it like this:
function greet ( person, message ) {
var greeting = 'Hello, ' + person + '!';
log( greeting + ' ' + message );
};
What are the differences between these two implementations?
There aren't any differences between those snippets, except hoisting which allows you to call the former function in the lines before the definition. But this is just a simplistic example to get you warmed up. In reality, people don't assign these functions to variables but pass them directly to other functions. Or they otherwise use them in expression contexts. Or they dynamically decide which function to to store. Or anything else really.
There is no real difference but the var form enables you to declare-before-use incase you have recursive functions.
Simple example:
var func1, func2;
func1 = function (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
func2 = function (count) {
func1(count + 1);
}
func1(10);
Although
function func1 (count) {
count = count - 2;
if (count > 0) {
func2(count);
}
}
function func2 (count) {
func1(count + 1);
}
func1(10);
is perfectly acceptable too. The interpreter will replace it with the former because of variable hoisting.