How do I welcome different names in a function? - javascript

Below is my (not working) code. I'm trying to write a function that allows me to enter in any name into the console.log and then have that name attached to the message. Please see below for clarification:
function checkAge(name, age) {
name = {};
if (age >= 21) {
return ("Welcome," + {} + "!");
}
else return ("Go home," + {} + "!");
}
console.log(checkAge('Adrian', 22)); //Welcome,[object Object]!
Expected result should be 'Welcome, Adrian!' (and not Welcome, [object, Object]!). BUT I don't want to hard code names so I can't just write
name === 'Adrian' since it needs to work for any name. Any advice? Thank you! :)

Remove the name = {}; you are reassigning parameter name and not passing the parameter to the return of string.
function checkAge(name, age) {
if (age >= 21) {
return ("Welcome," + name + "!");
}
else return ("Go home," + name + "!");
}
console.log(checkAge('Adrian', 22));
output >> Welcome,Adrian!

Related

Javascript Strigify Push and Shift given me error

I am new to javascript, please help me with this code, where did I get it wrong?
function magix2(arrangment, figures) {
arrangment.push(figures);
return arrangment.shift();
}
var bum = [26,27,28,29,30,31,32];
console.log("Before: " + JSON.stringify(arrangment));
console.log(magix2(bum, 33));
console.log("After: " + JSON.stringify(arrangment));
function magix2(arrangment, figures) {
arrangment.push(figures);
return arrangment.shift();
}
var bum = [26,27,28,29,30,31,32];
//console.log("Before: " + JSON.stringify(arrangment));
console.log(magix2(bum, 33));
//console.log("After: " + JSON.stringify(arrangment));
arrangment is the argument of function, you can't access that argument outside the function, that's I commented out these console lines.
arrangment is an argument of magix2 function you can not access it outside. Try accessing bum instead.
function magix2(arrangment, figures) {
arrangment.push(figures);
return arrangment.shift();
}
var bum = [26,27,28,29,30,31,32];
console.log("Before: " + JSON.stringify(bum));
console.log(magix2(bum, 33));
console.log("After: " + JSON.stringify(bum));
The correct way to perform your operation. Console Return 26, as it is first element, also 33 is added to list

JavaScript output of a string instead of undefined?

I'm getting undefined instead of a String on return of the answer - though it is the right correct characters being logged. How do I get it to output a definite string?
var greet = function(name) {
let first = String(name. charAt(0). toUpperCase());
let second = String(name.slice(1));
console.log('Hello ' + first + second + '!');
}
You forgot to return a value, so the return-value is undefined.
var greet = function(name) {
let first = String(name. charAt(0). toUpperCase());
let second = String(name.slice(1));
return 'Hello ' + first + second + '!';
}
console.log(greet('Gemma'));
The console will print the result of evaluating an expression. You can notice if you set
let name = 'john'
it will print undefined in the very next line.
That is also happening here. First it is printing your value, then it print undefined.
Your function is working fine - you just need to invoke it and feed its argument with a name...
[for the result look in the console]
var greet = function(name) {
let first = String(name.charAt(0).toUpperCase());
let second = String(name.slice(1));
console.log('Hello ' + first + second + '!');
}
;
greet("henky");

Why can't println(); be used as a variable?

I'm fairly new to Javascript, and am confused on something. Why can't the command "println("..."); be called as a variable such as: var num = println("...");. I could be wrong, and if you are able to, I'd be happy to know how. But after some testing it seems like I can't. My test code is:
function start() {
var SENTINEL = "1 1";
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = println(rollOne + rollTwo);
if(num == SENTINEL) {
println("You did it");
}
}
All it's supposed to do is give to random numbers in a # # form and, if it sees that the numbers are 1,1, it will give a message. It wont give the message and can't seem to view the variable "num" as an actual variable. But when I change the variable num to simply asking the user for a number:
function start() {
var SENTINEL = -1;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = readInt("Enter number");
if(num == SENTINEL) {
println("You did it");
}
}
And type in -1, it triggers the sentinel, thus promptly displaying the message. This is a really roundabout way to ask a simple question but I hope I can get some help. Thank you :)
Why can't the command "println("..."); be called as a variable such as: var num = println("...");
[...] It wont give the message and can't seem to view the variable
If the value returned is unusable, it is most likely undefined; i.e. The function println doesn't explicitly return anything.
In your case, you could try something like this:
var printInt = function(num) { println(num); return num; }
Note, println isn't part of the standard JavaScript language. For modern web browsers, it can be adapted to use (console.log(...)).
var printInt = function(num) { console.log(num); return num; }
And then to adapt to your code:
var num = printInt(rollOne + rollTwo);
But this still won't validate because you're comparing against "1 1" whereas your logic will return 2. JavaScript (as well as many other languages) implicitly uses addition when supplied with two numbers, but concatenation when supplied with at least one string.
var SENTINEL = "1 1"; // <---- String!
var SENTINEL = -1; // <---- Number!
So you should consider something like this instead (renamed accordingly):
var printRolls = function(text) { println(text); return text; }
var rolls = printRolls(rollOne + " " + rollTwo);
if(rolls == SENTINEL) {
println("You did it");
}
Or to simplify it a bit:
if(printRolls(rollOne + " " + rollTwo) == SENTINEL)
println("You did it");
It is possible that println doesn't return the string that is passed into. In that case, you can use
if (SENTINEL === rollOne + " " + rollTwo)
to format the string and properly test equality.
In JavaScript it is possible to assign the return value from any function to a variable similar to how you've done it:
var anyVariable = anyFunction();
But, some functions return the value undefined. Or they return a number, or an array, or...whatever.
I imagine your println() function prints the value you pass to it somewhere (on the screen? to the console?) and then returns undefined. Or if it is returning the printed value it is in a format different to what you have used in your SENTINEL variable. So then when you try to compare that with SENTINEL it won't be equal.
To fix your original function, assign the sum of the rolls to a variable, then print and test that:
function start() {
var SENTINEL = 2;
var rollOne = Randomizer.nextInt(1, 6);
var rollTwo = Randomizer.nextInt(1, 6);
var num = rollOne + rollTwo;
println(num);
if(num == SENTINEL) {
println("You did it");
}
}
EDIT: if you want the println() to display a string like "1 1" or "3 5" to show what each of the two rolls were then do this:
println(rollOne + " " + rollTwo);
That is, create a new string that is the result of concatenating rollOne's value with a single space and then rollTwo's value.

Match prompt input with an array value

I am playing with some basic js I am just beginning to learn, so far I have the code below. I am trying to ask the user what their name is and then tell them if they share the same name as a racing driver (from my array driversNames).
If they have the same name as a racing driver it would tell them they do, if not it would tell them they don't. However I have a feeling I have something wrong here: if (yourName === driversNames) but I cannot figure it out.
It doesn't matter what I enter into the prompt, it always says sorry you don't have the same name.
var driversNames = ["Lewis", "Fernando", "Sebastian", "Jenson", "Daniel"]
for (var i = 0; i < driversNames.length; i++) {
console.log(driversNames[i] + " " + "is a drivers name");
}
var yourName = prompt("What is your name?")
console.log("Your name is" + " " + yourName)
if (yourName === driversNames) {
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!")
} else {
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers")
}
You made one mistake in this line if (yourName === driversNames).
It doesnt compare your name with names from driversNames. The most easiest way: its use indexOf method. So this line should be like below
if (driversNames.indexOf(yourName) > -1) //Get Name otherwise no
And jsfiddle example for you, also indefOf link
Thanks
You are comparing a string to an array, so the comparison will return false. You have a few options to fix this though - I'll explain using a loop to check each string, and using indexOf.
Loop: You need to loop through each element in the driversNames array and compare each one. This is the manual way.
var sameName = false; //flag to keep track of if name matches or not
driversNames.forEach(function(name) { //loop through each name in driversNames
if(yourName === name) { //compare your name to driver name
sameName = true; //if match, set flag to true
}
}); //loop ends here
if(sameName) { //if flag is true, a name matched
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //Console log success statement
} else { // else, no name matched
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}
IndexOf: This method uses less lines of code, but isn't compatible on all browsers - I believe anything under IE8 will break when using this for example. But if compatibility isn't an issue, it looks like this:
if (driversNames.indexOf(yourName) > -1) { //indexof returns -1 for no match, and a number for match
console.log("Awesome" + " " + yourName + " " + "you share the same name as a Formula 1 driver!"); //console log success statement
} else {
console.log("Sorry" + " " + yourName + " " + "you don't have the same name as any Formula 1 drivers"); //console log fail statement
}
indexof is a little more elegant, although easy to forget the compatibility issue. Code is commented but just to explain it: Arrays have a method you can call, called indexOf() which takes a parameter. This method will then check if that parameter is in the array and if it is, return a value which is it's position in the array. If it isn't in the array, it will return -1.

Checking for the match of the Object name

Here I want to check the match for the particular class name (last class with the name of YtoD) and write a condition according to it. I have not Idea why it is not working.
HTML:
Select Range: Last Month | Last 2 Weeks | Last 1 Week| Year to Date
Javascript
function Lab(obj) {
var a = obj.name;
if (a != YtoD) {
document.getElementById("linechartxaxislabel").innerHTML = "Price
Timeline" + "(Last" + a + ")";
} else {
document.getElementById("linechartxaxislabel").innerHTML = "Year
to Date";
}
}
What should I do here?
Try this
function Lab(obj) {
var a = obj.getAttribute('name');
if (a != 'YtoD') {
document.getElementById("linechartxaxislabel").innerHTML = "Price Timeline" + "(Last" + a + ")";
} else {
document.getElementById("linechartxaxislabel").innerHTML = "Year to Date";
}
}
Firstly, the object you get in does not have a javascript attribute called name, as it's a DOM element. You need to access attributes using the DOM API (https://developer.mozilla.org/en-US/docs/Web/API/element.getAttribute)
Second, once you have the name it's a String so you need to compare it with the String YtoD and not an object reference.

Categories