Javascript - variable scope - javascript

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!

Related

Calling Javascript function returns a function with undefined values

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)();

why i am getting undefined value

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

JS function: why this won't alert my greeting?

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.

send parametres as values using JSON syntax

i want to send an url with parametres, those parametres are values taken by a form with javascript and i want to use JSON to do it, but when i debug i see this error : Uncaught ReferenceError: name is not defined..
function recup()
{
var selectElmt = document.getElementById("name");
var selectcat = document.getElementById("msg");
var name = selectElmt.options[selectElmt.selectedIndex].value;
var msg = selectcat.options[selectcat.selectedIndex].value;
}
function go() { // button send who call the function go
var p_url="http://mysite.com/class?name=" + name + "&message=" + msg +
$.getJSON(p_url, {
}).done(function( data ) {
$.each(data, function (key, field) {
alert(field);
});
});
return false;
}
it's a syntax error when calling the value name and msg but i don"t know how to fix it or in the go function
You two errors, closing curly brace and plus character, the code shoud be:
var msg = "hello"; // i just simplified the value
var name = "test";
function go() { // button send who call the function go
var p_url="http://mysite.com/class?name=" + name + "&message=" + msg;
$.getJSON(p_url, {
}).done(function( data ) {
$.each(data, function (key, field) {
alert(field);
});
});
return false;
}
UPDATE: You need to make name and msg global:
var name, msg;
function recup() {
var selectElmt = document.getElementById("name");
var selectcat = document.getElementById("msg");
name = selectElmt.options[selectElmt.selectedIndex].value;
msg = selectcat.options[selectcat.selectedIndex].value;
}
function go() { // button send who call the function go
var p_url="http://mysite.com/class?name=" + name + "&message=" + msg;
$.getJSON(p_url, {
}).done(function( data ) {
$.each(data, function (key, field) {
alert(field);
});
});
return false;
}
and recup need to be executed before go
the two variables are in another function
Well, that explains it. A variable that is local to a function cannot be accessed by another function.
You have to define the variables in a scope that is shared by both functions. This could be the global scope, but you should avoid creating global variables (you cannot have a global variable with name name anyways, because it exists already).
If you want to assign a value to a variable in a higher scope, use name = ...; instead of var name = ...;.
Example:
(function() {
// create a new scope so that we don't pollute the global scope
// this variable can be accessed by both functions
var answer;
function foo() {
// don't use `var` here, otherwise you create a local variable which
// shadows the variable with the same name in a higher scope
answer = 42;
}
function bar() {
alert(answer);
}
foo();
bar();
}());

Why should I assign a function to a variable in javascript? [duplicate]

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.

Categories