Category Archives: LinkedIn

LinkedIn Machine Learning Assessment

You are part of data science team that is working for a national fast-food chain. You create a simple report that shows trend: Customers who visit the store more often and buy smaller meals spend more than customers who visit less frequently and buy larger meals. What is the most likely diagram that your team created?

  • multiclass classification diagram
  • linear regression and scatter plots
  • pivot table
  • K-means cluster diagram

You work for an organization that sells a spam filtering service to large companies. Your organization wants to transition its product to use machine learning. It currently a list Of 250,00 keywords. If a message contains more than few of these keywords, then it is identified as spam. What would be one advantage of transitioning to machine learning?

  • The product would look for new patterns in spam messages.
  • The product could go through the keyword list much more quickly.
  • The product could have a much longer keyword list.
  • The product could find spam messages using far fewer keywords.

You work for a music streaming service and want to use supervised machine learning to classify music into different genres. Your service has collected thousands of songs in each genre, and you used this as your training data. Now you pull out a small random subset of all the songs in your service. What is this subset called?

  • data cluster
  • Supervised set
  • big data
  • test data

In traditional computer programming, you input commands. What do you input with machine learning?

  • patterns
  • programs
  • rules
  • data

Your company wants to predict whether existing automotive insurance customers are more likely to buy homeowners insurance. It created a model to better predict the best customers contact about homeowners insurance, and the model had a low variance but high bias. What does that say about the data model?

  • It was consistently wrong.
  • It was inconsistently wrong.
  • It was consistently right.
  • It was equally right end wrong.

You want to identify global weather patterns that may have been affected by climate change. To do so, you want to use machine learning algorithms to find patterns that would otherwise be imperceptible to a human meteorologist. What is the place to start?

  • Find labeled data of sunny days so that the machine will learn to identify bad weather.
  • Use unsupervised learning have the machine look for anomalies in a massive weather database.
  • Create a training set of unusual patterns and ask the machine learning algorithms to classify them.
  • Create a training set of normal weather and have the machine look for similar patterns.

You work in a data science team that wants to improve the accuracy of its K-nearest neighbor result by running on top of a naive Bayes result. What is this an example of?

  • regression
  • boosting
  • bagging
  • stacking

 \_\_\_\_ looks at the relationship between predictors and your outcome.

  • Regression analysis
  • K-means clustering
  • Big data
  • Unsupervised learning

What is an example of a commercial application for a machine learning system?

  • a data entry system
  • a data warehouse system
  • a massive data repository
  • a product recommendation system

What does this image illustrate?

  • a decision tree
  • reinforcement learning
  • K-nearest neighbor
  • a clear trendline

You work for a power company that owns hundreds of thousands of electric meters. These meters are connected to the internet and transmit energy usage data in real-time. Your supervisor asks you to direct project to use machine learning to analyze this usage data. Why are machine learning algorithms ideal in this scenario?

  • The algorithms would help the meters access the internet.
  • The algorithms will improve the wireless connectivity.
  • The algorithms would help your organization see patterns of the data.
  • By using machine learning algorithms, you are creating an IoT device.

To predict a quantity value. use \_\_\_\_.

  • regression
  • clustering
  • classification
  • dimensionality reduction

Why is naive Bayes called naive?

  • It naively assumes that you will have no data.
  • It does not even try to create accurate predictions.
  • It naively assumes that the predictors are independent from one another.
  • It naively assumes that all the predictors depend on one another.

You work for an ice cream shop and created the chart below, which shows the relationship between the outside temperature and ice cream sales. What is the best description of this chart?

  • It is a linear regression chart.
  • It is a supervised trendline chart.
  • It is a decision tree.
  • It is a clustering trend chart.

How is machine learning related to artificial intelligence?

  • Artificial intelligence focuses on classification, while machine learning is about clustering data.
  • Machine learning is a type of artificial intelligence that relies on learning through data.
  • Artificial intelligence is form of unsupervised machine learning.
  • Machine learning and artificial intelligence are the same thing.

How do machine learning algorithms make more precise predictions?

  • The algorithms are typically run more powerful servers.
  • The algorithms are better at seeing patterns in the data.
  • Machine learning servers can host larger databases.
  • The algorithms can run on unstructured data.

You work for an insurance company. Which machine learning project would add the most value for the company!

  • Create an artificial neural network that would host the company directory.
  • Use machine learning to better predict risk.
  • Create an algorithm that consolidates all of your Excel spreadsheets into one data lake.
  • Use machine learning and big data to research salary requirements.

What is the missing information in this diagram?

  • Training Set
  • Unsupervised Data
  • Supervised Learning
  • Binary Classification

What is one reason not to use the same data for both your training set and your testing set?

  • You will almost certainly underfit the model.
  • You will pick the wrong algorithm.
  • You might not have enough data for both.
  • You will almost certainly overfit the model.

Your university wants to use machine learning algorithms to help sort through incoming student applications. An administrator asks if the admissions decisions might be biased against any particular group, such as women. What would be the best answer?

  • Machine learning algorithms are based on math and statistics, and so by definition will be unbiased.
  • There is no way to identify bias in the data.
  • Machine learning algorithms are powerful enough to eliminate bias from the data.
  • All human-created data is biased, and data scientists need to account for that.

Explanation: While machine learning algorithms don’t have bias, the data can have them.

What is stacking?

  • The predictions of one model become the inputs another.
  • You use different versions of machine learning algorithms.
  • You use several machine learning algorithms to boost your results.
  • You stack your training set and testing set together.

You want to create a supervised machine learning system that identifies pictures of kittens on social media. To do this, you have collected more than 100,000 images of kittens. What is this collection of images called?

  • training data
  • linear regression
  • big data
  • test data

You are working on a project that involves clustering together images of different dogs. You take image and identify it as your centroid image. What type machine learning algorithm are you using?

  • centroid reinforcement
  • K-nearest neighbor
  • binary classification
  • K-means clustering

Explanation: The problem explicitly states “clustering”.

Your company wants you to build an internal email text prediction model to speed up the time that employees spend writing emails. What should you do?

  • Include training email data from all employees.
  • Include training email data from new employees.
  • Include training email data from seasoned employees.
  • Include training email data from employees who write the majority of internal emails.

Your organization allows people to create online professional profiles. A key feature is the ability to create clusters of people who are professionally connected to one another. What type of machine learning method is used to create these clusters?

  • unsupervised machine learning
  • binary classification
  • supervised machine learning
  • reinforcement learning

What is this diagram a good example of?

  • K-nearest neighbor
  • a decision tree
  • a linear regression
  • a K-means cluster

Note: there are centres of clusters (C0, C1, C2).

Random forest is modified and improved version of which earlier technique?

  • aggregated trees
  • boosted trees
  • bagged trees
  • stacked trees

Self-organizing maps are specialized neural network for which type of machine learning?

  • semi-supervised learning
  • supervised learning
  • reinforcement learning
  • unsupervised learning

Which statement about K-means clustering is true?

  • In K-means clustering, the initial centroids are sometimes randomly selected.
  • K-means clustering is often used in supervised machine learning.
  • The number of clusters are always randomly selected.
  • To be accurate, you want your centroids outside of the cluster.

You created machine learning system that interacts with its environment and responds to errors and rewards. What type of machine learning system is it?

  • supervised learning
  • semi-supervised learning
  • reinforcement learning
  • unsupervised learning

Your data science team must build a binary classifier, and the number one criterion is the fastest possible scoring at deployment. It may even be deployed in real time. Which technique will produce a model that will likely be fastest for the deployment team use to new cases?

  • random forest
  • logistic regression
  • KNN
  • deep neural network

Your data science team wants to use the K-nearest neighbor classification algorithm. Someone on your team wants to use a K of 25. What are the challenges of this approach?

  • Higher K values will produce noisy data.
  • Higher K values lower the bias but increase the variance.
  • Higher K values need a larger training set.
  • Higher K values lower the variance but increase the bias.

Your machine learning system is attempting to describe a hidden structure from unlabeled data. How would you describe this machine learning method?

  • supervised learning
  • unsupervised learning
  • reinforcement learning
  • semi-unsupervised learning

You work for a large credit card processing company that wants to create targeted promotions for its customers. The data science team created a machine learning system that groups together customers who made similar purchases, and divides those customers based on customer loyalty. How would you describe this machine learning approach?

  • It uses unsupervised learning to cluster together transactions and unsupervised learning to classify the customers.
  • It uses only unsupervised machine learning.
  • It uses supervised learning to create clusters and unsupervised learning for classification.
  • It uses reinforcement learning to classify the customers.

You are using K-nearest neighbor and you have a K of 1. What are you likely to see when you train the model?

  • high variance and low bias
  • low bias and low variance
  • low variance and high bias
  • high bias and high variance

Are data model bias and variance a challenge with unsupervised learning?

  • No, data model bias and variance are only a challenge with reinforcement learning.
  • Yes, data model bias is a challenge when the machine creates clusters.
  • Yes, data model variance trains the unsupervised machine learning algorithm.
  • No, data model bias and variance involve supervised learning.

Which choice is best for binary classification?

  • K-means
  • Logistic regression
  • Linear regression
  • Principal Component Analysis (PCA)

Explanation: Logistic regression is far better than linear regression at binary classification since it biases the result toward one extreme or the other. K-means clustering can be used for classification but is not as accurate in most scenarios.

With traditional programming, the programmer typically inputs commands. With machine learning, the programmer inputs

  • supervised learning
  • data
  • unsupervised learning
  • algorithms

Explanation: This one is pretty straight forward and a fundamental concept.

Why is it important for machine learning algorithms to have access to high-quality data?

  • It will take too long for programmers to scrub poor data.
  • If the data is high quality, the algorithms will be easier to develop.
  • Low-quality data requires much more processing power than high-quality data.
  • If the data is low quality, you will get inaccurate results.

In K-nearest neighbor, the closer you are to neighbor, the more likely you are to

  • share common characteristics
  • be part of the root node
  • have a Euclidean connection
  • be part of the same cluster

In the HBO show Silicon Valley, one of the characters creates a mobile application called Not Hot Dog. It works by having the user take a photograph of food with their mobile device. Then the app says whether the food is a hot dog. To create the app, the software developer uploaded hundreds of thousands of pictures of hot dogs. How would you describe this type of machine learning?

  • Reinforcement machine learning
  • unsupervised machine learning
  • supervised machine learning
  • semi-supervised machine learning

You work for a large pharmaceutical company whose data science team wants to use unsupervised learning machine algorithms to help discover new drugs. What is an advantage to this approach?

  • You will be able to prioritize different classes of drugs, such as antibiotics.
  • You can create a training set of drugs you would like to discover.
  • The algorithms will cluster together drugs that have similar traits.
  • Human experts can create classes of drugs to help guide discovery.

Explanation: This one is similar to an example talked about in the Stanford Machine Learning course.

In 2015, Google created a machine learning system that could beat a human in the game of Go. This extremely complex game is thought to have more gameplay possibilities than there are atoms of the universe. The first version of the system won by observing hundreds of thousands of hours of human gameplay; the second version learned how to play by getting rewards while playing against itself. How would you describe this transition to different machine learning approaches?

  • The system went from supervised learning to reinforcement learning.
  • The system evolved from supervised learning to unsupervised learning.
  • The system evolved from unsupervised learnin9 to supervised learning.
  • The system evolved from reinforcement learning to unsupervised learning.

The security company you work for is thinking about adding machine learning algorithms to their computer network threat detection appliance. What is one advantage of using machine learning?

  • It could better protect against undiscovered threats.
  • It would very likely lower the hardware requirements.
  • It would substantially shorten your development time.
  • It would increase the speed of the appliance.

You work for a hospital that is tracking the community spread of a virus. The hospital created a smartwatch app that uploads body temperature data from hundreds of thousands of participants. What is best technique to analyze the data?

  • Use reinforcement learning to reward the system when a new person participates
  • Unsupervised machine learning to cluster together people based on patterns the machine discovers
  • Supervised machine learning to sort people by demographic data
  • supervised ml to classify people by body temperature

Man of the advances in ml have come from improved

  • statistics
  • structured data
  • availability
  • algorithms

What is this diagram a good example of?

  • unsupervised learning
  • complex cluster
  • multiclass classification
  • k-nearest neighbour

The supervisor asks to create a ml system that will help your hr dep. classify job applicants into well-defined groups.What type of system are more likely to recommend?

  • deep learning artificial neural network that relies on petabytes of data
  • unsupervised ml system that clusters together the best candidates
  • Not recommend ml for this project
  • supervised ml system that classifies applicants into existing groups // we do not need to classify best candidates we just need to classify job applicants in to existing categories

Someone of your data science team recommends that you use decision trees, naive Bayes and K-nearest neighbor, all at the same time, on the same training data, and then average the results. What is this an example of?

  • regression analysis
  • unsupervised learning
  • high -variance modeling
  • ensemble modeling

Your data science team wants to use ml to better filter out spam messages. The team has gathered a database of 100,000 messages that have been identified as spam or not spam. If you are using supervised ml, what would you call this data set?

  • ml algorithm
  • training set
  • big data test set
  • data cluster

You work for a website that enables customers see all images of themselves on the internet by uploading one self-photo. Your data model uses 5 characteristics to match people to their foto: color, eye, gender, eyeglasses and facial hair. Your customers have been complaining that get tens of thousands of fotos without them. What is the problem?

  • You are overfitting the model to the data
  • You need a smaller training set
  • You are underfitting the model to the data
  • You need a larger training set

Your supervisor asks you to create a machine learning system that will help your human resources department classify jobs applicants into well defined groups. What type of system are you more likely to recommend?

  • an unsupervised machine learning system that clusters together the best candidates.
  • you would not recommend a machine learning system for this type of project.
  • a deep learning artificial neural network that relies on petabytes of employment data.
  • a supervised machine learning system that classifies applicants into existing groups.

You and your data science team have 1 TB of example data. What do you typically do with that data?

  • you use it as your training set.
  • You label it big data.
  • You split it into a training set and test set.
  • You use it as your test set.

Your data science team is working on a machine learning product that can act as an artificial opponent in video games. The team is using a machine learning algorithm that focuses on rewards: If the machine does some things well, then it improves the quality of the outcome. How would you describe this type of machine learning algorithm?

  • semi-supervised machine learning
  • supervised machine learning
  • unsupervised machine learning
  • reinforcement learning

The model will be trained with data in one single batch is known as ?

  • Batch learning
  • Offline learning
  • Both A and B
  • None of the above

Which of the following is NOT supervised learning? ?

  • Decision Tree
  • Linear Regression
  • PCA
  • Naive Bayesian

Suppose we would like to perform clustering on spatial data such as the geometrical locations of houses. We wish to produce clusters of many different sizes and shapes. Which of the following methods is the most appropriate? ?

  • Decision Trees
  • K-means clustering
  • Density-based clustering
  • Model-based clustering

The error function most suited for gradient descent using logistic regression is

  • The entropy function.
  • The squared error.
  • The cross-entropy function.
  • The number of mistakes.

Compared to the variance of the Maximum Likelihood Estimate (MLE), the variance of the Maximum A Posteriori (MAP) estimate is ____

  • Higher
  • same
  • Lower
  • it could be any of the above

**___** refers to a model that can neither model the training data nor generalize to new data.

  • good fitting
  • overfitting
  • underfitting
  • all of the above

How would you describe this type of classification challenge?

  • This is a multiclass classification challenge.
    Explanation: Shows data being classified into more than two categories or classes. Thus, this is a multi-class classification challenge.
  • This is a multi-binary classification challenge.
  • This is a binary classification challenge.
  • This is a reinforcement classification challenge.

What does it mean to underfit your data model?

  • There is too little data in your training set.
  • There is too much data in your training set.
  • There is not a lot of variance but there is a high bias.
    // Underfitted data models usually have high bias and low variance. Overfitted data models have low bias and high variance.
  • Your model has low bias but high variance.

Asian user complains that your company’s facial recognition model does not properly identify their facial expressions. What should you do?

  • Include Asian faces in your test data and retrain your model.
  • Retrain your model with updated hyperparameter values.
  • Retrain your model with smaller batch sizes.
  • Include Asian faces in your training data and retrain your model.
    // The answer is self-explanatory: if Asian users are the only group of people making the complaint, then the training data should have more Asian faces.

You work for a website that helps match people up for lunch dates. The website boasts that it uses more than 500 predictors to find customers the perfect date, but many costumers complain that they get very few matches. What is a likely problem with your model?

  • Your training set is too large.
  • You are underfitting the model to the data.
  • You are overfitting the model to the data.
  • Your machine is creating inaccurate clusters.

(Mostly) whenever we see kernel visualizations online (or some other reference) we are actually seeing:

  • What kernels extract
  • Feature Maps
  • How kernels Look

The activations for class A, B and C before softmax were 10,8 and 3. The different in softmax values for class A and class B would be :

  • 76%
  • 88%
  • 12%
  • 0.0008%

The new dataset you have just scraped seems to exhibit lots of missing values. What action will help you minimizing that problem?

  • Wise fill-in of controlled random values
  • Replace missing values with averaging across all samples
  • Remove defective samples
  • Imputation

Which of the following methods can use either as an unsupervised learning or as a dimensionality reduction technique?

  • SVM
  • PCA
  • LDA
  • TSNE

What is the main motivation for using activation functions in ANN?

  • Capturing complex non-linear patterns
  • Transforming continuous values into “ON” (1) or “OFF” (0) values
  • Help avoiding the vanishing/exploding gradient problem
  • Their ability to activate each neurons individually.

Which loss function would fit best in a categorical (discrete) supervised learning ?

  • kullback-leibler (KL) loss
  • Binary Crossentropy
  • Mean Squared Error (MSE)
  • Any L2 loss

What is the correct option?

no. Red Blue Green
1. Validation error Training error Test error
2. Training error Test error Validation error
3. Optimal error Validation error Test error
4. Validation error Training error Optimal error
  • 1
  • 2
  • 3
  • 4

You create a decision tree to show whether someone decides to go to the beach. There are three factors in this decision: rainy, overcast, and sunny. What are these three factors called?

  • tree nodes
  • predictors // these nodes decide whether the someone decides to go to beach or not, for example if its rainy people will mostly refrain from going to beach
  • root nodes
  • deciders

Q69. You need to quickly label thousands of images to train a model. What should you do?

  • Set up a cluster of machines to label the images
  • Create a subset of the images and label then yourself
  • Use naive Bayes to automatically generate labels.
  • Hire people to manually label the images

Q70. The fit line and data in the figure exhibits which pattern?

  • low bias, high variance
  • high bias, low variance
  • high bias, high variance
  • low bias, low variance // since the data is accurately classified and is neither overfitting or underfitting the dataset

Q71. Many of the advances in machine learning have come from improved?

  • structured data
  • algorithms
  • time
  • computer scientists

Q72. You need to select a machine learning process to run a distributed neural network on a mobile application. Which would you choose?

  • Scikit-learn
  • PyTorch
  • Tensowflow Lite
  • Tensorflow

Q73. Which choice is the best example of labeled data?

  • a spreadsheet
  • 20,000 recorded voicemail messages
  • 100,000 images of automobiles
  • hundreds of gigabytes of audio files

Q74. In statistics, what is defined as the probability of a hypothesis test of finding an effect – if there is an effect to be found?

  • confidence
  • alpha
  • power
  • significance

Q75. You want to create a machine learning algorithm to identify food recipes on the web. To do this, you create an algorithm that looks at different conditional probabilities. So if the post includes the word flour, it has a slightly stronger probability of being a recipe. If it contains both flour and sugar, it even more likely a recipe. What type of algorithm are you using?

  • naive Bayes classifier
  • K-nearest neighbor
  • multiclass classification
  • decision tree

Q76. What is lazy learning?

  • when the machine learning algorithms do most of the programming
  • when you don’t do any data scrubbing
  • when the learning happens continuously
  • when you run your computation in one big instance at the beginning
Spread the love

AngularJs – LinkedIn Skill Assessment

Q1. What is the purpose of the ViewChild decorator in this component class?

    @Component({
    . . .
    template: '<p #bio></p>'
    })
    export class UserDetailsComponent {
    @ViewChild('bio') bio;
    }
  • It provides access from within the component class to the ElementRef object for thetag that has the bio template reference variable in the component’s template view. It provides access from within the component class to the null object for the null tag that has the null template reference variable in the component’s template view.
  • It indicates that thetag be rendered as a child of the parent view that uses this component. It indicates that the null tag be rendered as a child of the parent view that uses this component.
  • It makes thetag in the template support content projection. It makes the null tag in the template support content projection.
  • It makes thetag visible in the final render. If the #bio was used in the template and the @ViewChild was not used in the class, then Angular would automatically hide thetag that has #bio on it.

Q2. What method is used to wire up a FormControl to a native DOM input element in reactive forms? What method is used to wire up a null to a native DOM input element in reactive forms?

  • Add the string name given to the FormControl to an attribute named controls on the element to indicate what fields it should include. Add the string name given to the null to an attribute named controls on the null element to indicate what fields it should include.
  • Use the square bracket binding syntax around the value attribute on the DOM element and set that equal to an instance of the FormControl. Use the square bracket binding syntax around the value attribute on the DOM element and set that equal to an instance of the null.
  • Use the formControlName directive and set the value equal to the string name given to the FormControl. Use the null directive and set the value equal to the string name given to the null.
  • Use the string name given to the FormControl as the value for the DOM element id attribute.

Q3. What is the difference between the paramMap and the queryParamMap on the ActivatedRoute class? What is the difference between the null and the null on the null class?

  • The paramMap is an object literal of the parameters in a route’s URL path. The queryParamMap is an Observable of those same parameters. The null is an object literal of the parameters in a route’s URL path. The null is a null of those same parameters.
  • The paramMap is an Observable that contains the parameter values that are part of a route’s URL path. The queryParamMap is a method that takes in an array of keys and is used to find specific parameters in the paramMap. The null is a null that contains the parameter values that are part of a route’s URL path. The null is a method that takes in an array of keys and is used to find specific parameters in the null.
  • paramMap is the legacy name from Angular 3. The new name is queryParamMap.null is the legacy name from Angular 3. The new name is null.
  • Both are Observables containing values from the requested route’s URL string. The paramMap contains the parameter values that are in the URL path and the queryParamMap contains the URL query parameters.

Q4. Based on the following usage of the async pipe, and assuming the users class field is an Observable, how many subscriptions to the users Observable are being made?

    <h2>Names</h2>
    <div *ngFor="let user of users | async">{{ user.name }}</div>
    <h2>Ages</h2>
    <div *ngFor="let user of users | async">{{ user.age }}</div>
    <h2>Genders</h2>
    <div \*ngFor="let user of users | async">{{ user.gender }}</div>
  • None. The async pipe does not subscribe automatically. None. The null pipe does not subscribe automatically.
  • None. The template syntax is not correct. None. The template syntax is not correct.
  • Three. There is one for each async pipe. Three. There is one for each null pipe.
  • One. The async pipe caches Observables by type internally.

Q5. How can you use the HttpClient to send a POST request to an endpoint from within an addOrder function in this OrderService?

export class OrderService {
    constructor(private httpClient: HttpClient) { }
    addOrder(order: Order) {
    // Missing line
    }
}
  • this.httpClient.url(this.orderUrl).post(order);null
  • this.httpClient.send(this.orderUrl, order);null
  • this.httpClient.post(this.orderUrl, order);null
  • this.httpClient.post(this.orderUrl, order) .subscribe();

Q6. What is the RouterModule.forRoot method used for? What is the null method used for?

  • registering any providers that you intend to use in routed components registering any providers that you intend to use in routed components
  • registering route definitions at the root application level registering route definitions at the root application level
  • indicating that Angular should cheer on your routes to be successful indicating that Angular should cheer on your routes to be successful
  • declaring that you intend to use routing only at the root level

Q7. Which DOM elements will this component metadata selector match on?

    @Component({
    selector: 'app-user-card',
    . . .
    })
  • any element with the attribute app-user-card, such as

    any element with the attribute null, such as null

  • the first instance of the first instance of null
  • all instances of all instances of null
  • all instances of

Q8. What is the correct template syntax for using the built-in ngFor structural directive to render out a list of productNames?What is the correct template syntax for using the built-in null structural directive to render out a list of null?

  • [ ]
<ul>
    <li [ngFor]="let productName of productNames">
    {{ productName }}
    </li>
</ul>
  • [ ]
<ul>
    <li ngFor="let productName of productNames">
    {{ productName }}
    </li>
</ul>
  • [ ]
<ul>
    <li *ngFor="let productName of productNames">
    {{ productName }}
    </li>
</ul>
  • [ ]
<ul>
    <? for productName in productNames { ?>
    <li>{{ productName }}</li>
    <? } ?>
</ul>

Q9. What are the two component decorator metadata properties used to set up CSS styles for a component? What are the two component decorator metadata properties used to set up CSS styles for a component?

  • viewEncapsulation and viewEncapsulationFilesnull and null
  • There is only one and it is the property named css. There is only one and it is the property named null.
  • css and cssUrlnull and null
  • styles and styleUrlsnull and null

Q10. With the following component class, what template syntax would you use in the template to display the value of the title class field?

    @Component({
    selector: 'app-title-card',
    template: ''
    })
    class TitleCardComponent {
    title = 'User Data';
    }
  • {{ ‘title’ }}null
  • {{ title }}null
  • [title]null
  • A class field cannot be displayed in a template via the template syntax.

Q11. What is the purpose of the valueChanges method on a FormControl? What is the purpose of the null method on a null?

  • It is used to configure what values are allowed for the control. It is used to configure what values are allowed for the control.
  • It is used to change the value of a control to a new value. You would call that method and pass in the new value for the form field. It even supports passing in an array of values that can be set over time. It is used to change the value of a control to a new value. You would call that method and pass in the new value for the form field. It even supports passing in an array of values that can be set over time.
  • It returns a Boolean based on if the value of the control is different from the value with which it was initialized. It returns a Boolean based on if the value of the control is different from the value with which it was initialized.
  • It is an observable that emits every time the value of the control changes, so you can react to new values and make logic decisions at that time. It is an null that emits every time the value of the control changes, so you can react to new values and make logic decisions at that time.

Q12. What directive is used to link an <a> tag to routing?

  • routeTo
  • routerLink
  • routePathn
  • appLink

Q13. What is the Output decorator used for in this component class?

    @Component({
    selector: 'app-shopping-cart',
    . . .
    })
    export class ShoppingCartComponent {
    @Output() itemTotalChanged = new EventEmitter();
    }
  • It makes the itemTotalChanged class field public. It makes the null class field public.
  • It provides a way to bind values to the itemTotalChanged class field, like so: <app-shopping-cart [itemTotalChanged]=”newTotal”>. It provides a way to bind values to the null class field, like so: null.
  • It provides a way to bind events to the itemTotalChanged class field, like so: <app-shopping-cart (itemTotalChanged)=”logNewTotal($event)”>. It provides a way to bind events to the null class field, like so: null.
  • It is simply a way to put a comment in front of a class field for documentation.

Q14. What is the difference between these two markup examples for conditionally handling display?

    <div \*ngIf="isVisible">Active</div>
    <div [hidden]="!isVisible">Active</div>
  • The ngIf is shorthand for the other example. When Angular processes that directive, it writes a div element to the DOM with the hidden property. The null is shorthand for the other example. When Angular processes that directive, it writes a null element to the DOM with the null property.
  • They are fundamentally the same. They are fundamentally the same.
  • The ngIf directive does not render the div in the DOM if the expression is false. The hidden property usage hides the div content in the browser viewport, but the div is still in the in the DOM. The null directive does not render the null in the DOM if the expression is null. The null property usage hides the null content in the browser viewport, but the null is still in the in the DOM.
  • The ngIf is valid, but the use of the hidden property is wrong and will throw an error.

Q15. How can you disable the submit button when the form has errors in this template-driven forms example?

<form #userForm="ngForm">
    <input type="text" ngModel name="firstName" required>
    <input type="text" ngModel name="lastName" required>
    <button (click)="submit(userForm.value)">Save</button>
</form>
  • [ ]
<button (click)="submit(userForm.value)"
  disable="userForm.invalid">
Save</button>
  • [ ]
 <button (click)="submit(userForm.value)"
  [disabled]="userForm.invalid">
Save</button>
  • [ ]
 <button (click)="submit(userForm.value)"
  [ngForm.disabled]="userForm.valid">
Save</button>
  • [ ]
 <button (click)="submit(userForm.value)"
  *ngIf="userForm.valid">
Save</button>
Spread the love

LinkedIn jQuery Assessment

Here we have given the collection of jQuery Questions and Answers asked in Linked in assessment. LinkedIn Assessment is a test of particular skill. After passing this skill you will get a Bade in your profile and that you can share with your network.

What’s the difference between these two snippets?

$('button').on('click', function(){ alert('you clicked the button!'); });
$('button').click(function(){ alert('you clicked the button!'); });
  • Only the second one will work; jQuery does not have a function called .on.
  • The second snippet will not function.
  • Nothing .click(function) is shorter way to write .on('click', function).
  • The first snippet will execute for every button on the page, the second will only apply to the first button.

What does the following line of code do?

jQuery('p')

  • Loads a paragraph tag from a remote server using AJAX
  • Aliases jQuery to a variable p
  • Selects all paragraphs on the page
  • Creates a new paragraph tag and inserts it into the body tag

Given the following HTML, how could we use one line to hide or show the button?

<button class="btn btn-primary" type="submit">Continue to checkout</button>
  • $('.btn-primary').toggle();
  • $('.btn-primary').showHide();
  • $('.btn-primary').not(':visible').show();
  • $('.btn-primary').css({ display: 'block'});

Working with AJAX, we may run into situations where a piece of code should not be run until after multiple AJAX calls have completed successfully. Say we need to call two external services for JSON data (a list of students, and a list of classes). And only after retrieving those data will we perform some manipulations on a page. What is the preferred way for dealing with this scenario?

https://example.com/json-api/students
https://example.com/json-api/classes

  • [ ]
$.get([ 'https://example.com/json-api/students', 'https://example.com/json-api/classes' ], function(studentRequest, classRequest) { 
  // the rest of the code goes here 
});
  • [ ]
$.when( $.get('https://example.com/json-api/students'), $.get('https://example.com/json-api/classes') ).done(function(studentRequest, classRequest) { 
  // the rest of the code goes here 
});
  • [ ]
$.bind( $.get('https://example.com/json-api/students'), $.get('https://example.com/json-api/classes') ).done(function(studentRequest, classRequest) { 
  // the rest of the code goes here 
});
  • [x]
$.ajax('https://example.com/json-api/students', { success: function(studentRequest) { $.ajax('https://example.com/json-api/classes', { success: function(classRequest) { 
  // the rest of the code goes here 
} }); } });

Given the snippet of HTML below, what is the difference between the two lines that follow it?

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>
$('ul').find('li').get(2);
$('ul').find('li').eq(2);
  • .get() retrieves a DOM element, and can’t be chained, eq() retrieves a jQuery object, and can be chained.
  • .get() retrieves a jQuery object, and can’t be chained, eq() retrieves a DOM element, and can be chained.
  • .get() retrieves a jQuery object, and is zero-indexed, eq() retrieves a DOM element, and is 1-indexed.
  • .get() retrieves a DOM element, and is zero-indexed, eq() retrieves a jQuery object, and is 1-indexed.

Suppose we want to have a ball created from an HTML element (id=ball) move down and to the right from its original location when clicked, and move back into its original place when finished. Given a starting point of this, which of these snippets would accomplish that goal?

$('#ball').click(function() {
  // Our code goes here
});
  • [x]
$(this).animate({ top: '+=100', left: '+=100', }, { duration: 600, complete: function() { $(this).animate({ top: '-=100', left: '-=100', }, 600) } });
  • [ ]
$(this).animate({ top: '-=100', left: '-=100', }, 600, function() { $(this).animate({ top: '+=100', left: '+=100', }, 600) });
  • [ ]
$(this).animate({ top: '=100', left: '=100', }, { duration: 600, complete: function() { $(this).animate({ top: 0, left: 0, }, 600) } });
  • [ ]
$(this).animate({ top: '100', left: '100', }, 600, function() { $(this).animate({ top: 0, left: 0, }, 600) });

Given the following CSS and HTML codes below, how could you apply the success class to the feedback div?

.success {
  color: green;
  background: #ddffdd;
}
<div class="feedback">
  Thank you for answering this survey.
</div>
  • $('.feedback').hasClass('.success');
  • $.css('.feedback', '.success');
  • $('.feedback').addClass('success');
  • $('.feedback').css('.success');

Below is an example page snippet that includes a couple of messages in a list, and a code snippet that retrieves a few hundred messages from a API endpoints using AJAX. How might we add these items to the page snippet in a way that avoids performance problems with DOM insertions?

<div class="message-area">
  <ul class="message-area--list">
    <li>Existing message 1</li>
    <li>Existing message 2</li>
  </ul>
</div>
$.get('//example.com/api/v1/message')
.done(function(data) {
  var tonsOfItems = data.messages;
  // add all these messages to a large page
});
  • tonsOfItems.map(function(item) { $('.message-area--list').append('<li>'+item+'</li>'); });
  • var tonsOfListItems = tonsOfItems.map(function(item)) { return '<li>'+item+'</li>'; }); $('.message-area--list').append(tonsOfListItems.join(''));
  • Removing the event handlers with JavaScript will be slower than removing them $.each(tonsOfItems, function(idx, item) { $('<li>'+item+'</li>').appendTo($messageList); });
  • $.each(tonsOfItems, function(idx, item) { $('.message-area--list').append('<li>'+item+'</li>'); });

What is jQuery?

  • jQuery is a bridge between Java and Javascript that makes native apps easier to write.
  • jQuery is a plugin for JavaScript that makes database queries easier to write.
  • jQuery is a collection of JavaScript functions that makes finding and manipulating elements on a page, AJAX, and other things easier.
  • jQuery is a Chrome extension that allows users to create their own extensions with just a few lines of JavaScript.

We want to create a new jQuery plugin called linkUpdater that can be chained onto other jQuery selector like a normal plugin. It should update all the links in the referenced collection so they open in new windows or tabs. Below is the first cut. What is one problem with this plugin?

"user strict";
($.linkUpdater = function() {
  this.find('a').attr('target', '_blank');
})( jQuery );
  • this needs to be wrapped, like $(this), in order to be chained in a plugin.
  • jQuery plugins can’t be safely authored in strict mode.
  • In order to be used by other code, plugins need to be added to the global namespace, not wrapped in a function expression.
  • Our plugin should extend jQuery.fn, not jQuery itself.

Generally speaking, when used on a web page, how should jQuery be installed, and why?

  • Just before the closing body tag, because we want to avoid blocking other resources from loading, and we use the ready method to make sure our code fires after the DOM is ready
  • Using the highest version number possible because only jQuery 3 and up are compatible with Internet Explorer 7
  • In the head tag because we want jQuery available as soon as possible
  • From a CDN because we want to be able to use jQuery online or offline

Given the following HTML, how could we make this button disappear from the page using jQuery?

<button class="btn btn-primary" type="submit">Continue to checkout</button>
  • $('.btn-primary').hide();
  • $('.btn-primary:visible').not();
  • $('.btn-primary').visibility(false);
  • $('.btn-primary').show(false);

What is the difference between $('header').html() and $('header').text()?

  • $('header').html() returns the inner HTML of the header. $('header').text() returns only the text
  • $('header').html() returns only the HTML tags used, without the text. $('header').text() returns only the text
  • $('header').html() strips all HTML from the header. $('header').text() always returns an empty string.
  • $('header').html() returns all headers in an HTML document. $('header').text() the first line of a text file.

When writing jQuery plugins, we often provide default options that may be overridden by the end user. What jQuery function is most useful for this purpose?

  • $.extend
  • $.clone
  • $.fn.extend
  • $.merge

There are times when you might want to programmatically trigger an event, instead of simply reacting to user input directly. Given this markup, Which choice will NOT cause a click event to the select box when the button is clicked?

<article>
  <div>
    Here's a button you can click: <button class="btn">Click Me</button>
  </div>
  <form>
    <p>
      Further down the page, there's a select box.
    </p>
    <select>
      <option value="1">One</option>
      <option value="2">One</option>
      <option value="3">One</option>
      <option value="4">One</option>
    </select>
  </form>
</article>
  • $('button').on('click.myApp', (function() { $('input[type=select]').trigger('click'); });
  • $('button').on('click', (function() { $('input[type=select]').click()); });
  • $('button').trigger(function() { $('input[type=select]').click(); });
  • $('button').click(function() { $('input[type=select]').click(); });

You have an absolutely positioned element inside a relatively positioned parent element, and you want to animate that element within its parent element. What jQuery function is most useful for finding the initial coordinates of the .animate-me?

<style>
  .parent {
    position: relative;
    top: 3em;
    width: 50%;
    min-height: 50vh;
    margin: 0 auto;
  }

  .animate-me {
    position: absolute;
    top: 40px;
    right: 30px;
  }
</style>

<div class="parent">
  <div class="animate-me">
    This box will move!
  </div>
</div>
  • $('.animate-me').offset();
  • $('.animate-me').each();
  • $('.animate-me').position();
  • $('.animate-me').offsetParent();

You want to work with AJAX using a Promise-like interface instead of nested callback functions. What jQuery API should you use?

  • jQuery.sub
  • jQuery.ajaxTransport
  • jQuery.Deferred
  • jQuery.proxy

What is tricky about jQuery’s nth- filters (:nth-child, :nth-of-type, etc.) relative to other filters?

  • Referring to lists of items, they are 1-indexed (like CSS), not 0-indexed (like JavaScript).
  • They don’t return the jQuery object, and cannot be chained.
  • They can return the wrong items if the DOM was recently manipulated.
  • They are not part of CSS, so they don’t get the performance benefits of passing through the document.querySelectorAll.

jQuery’s AJAX functions return objects that implement the Promise API. As a result, you can chain promises and avoid nested callbacks. What does that look like?

  • [x]
$.get('hhttp://httpbin.org/delay/2')
  .then(function(response) {
    // Data from first GET is here as 'response'
    return $.get('http://httpbin.org/delay/2');
  })
  .then(function(response) {
    // Data from second GET is here as 'response'
  });
  • [ ]
$.get('hhttp://httpbin.org/delay/2')
  .catch(function(response) {
    // Data from first GET is here as 'response'
    return $.get('http://httpbin.org/delay/2');
  })
  .done(function(response) {
    // Data from second GET is here as 'response'
  });
  • [ ]
$.get('hhttp://httpbin.org/delay/2', function(response1) {
  // Data from first GET is here as 'response1'

  $.get('http://httpbin.org/delay/2', function(response2) {
  // Data from second GET is here as 'response2'
  });
});
  • [ ]
$.get('hhttp://httpbin.org/delay/2')
  .then(function(response) {
    // Data from first GET is here as 'response'
    return response;
  })
  .get('http://httpbin.org/delay/2', function(response) {
    // Data from second GET is here as 'response'
  });

You want to have a ball that is created from an HTML element (id=ball) move down and to the right of its original location when clicked, and move back to its original place when finished. What snippet, added to the code below, would do this?

$('#ball').click(function() {
  // Our code goes here
});
  • [ ]
$(this).animate({
  top: '-=100',
  left: '-=100',
}, 600, function() {
  $(this).animate({
  top: '+=100',
  left: '+=100',
  }, 600)
});
  • [x]
$(this).animate({
  top: '+=100',
  left: '+=100',
}, {
  duration: 600,
  complete: function() {
  $(this).animate({
  top: '-=100',
  left: '-=100',
  }, 600)
  }
});
  • [ ]
$(this).animate({
  top: 100,
  left: 100,
}, 600, function() {
  $(this).animate({
  top: 0,
  left: 0,
  }, 600)
});
  • [ ]
$(this).animate({
  top: 100,
  left: 100,
}, {
  duration: 600,
  complete: function() {
  $(this).animate({
  top: 0,
  left: 0,
  }, 600)
  }
});

The way .wrap() works is sometimes misunderstood. Given the DOM and jQuery snippets below, what does the modified DOM snippet look like?

<div id="container">
  <div class="item">Here's an item</div>
</div>
$('#container').wrap('<div class="wrapper"></div>').css('border', '2px solid red');
  • [ ]
<div class="wrapper" style="border: 2px solid red;">
  <div id="container">
    <div class="item">Here's an item</div>
  </div>
</div>
  • [x]
<div class="wrapper">
  <div id="container" style="border: 2px solid red;">
    <div class="item">Here's an item</div>
  </div>
</div>
  • [ ]
<div id="container" style="border: 2px solid red;">
  <div class="wrapper">
    <div class="item">Here's an item</div>
  </div>
  </div>
  • [ ]
<div id="container">
  <div class="wrapper" style="border: 2px solid red;">
    <div class="item">Here's an item</div>
  </div>
</div>

How can you select the following blockquote AND the list in a single call to jQuery() without chaining?

<div class="quotes">
  <blockquote data-favorite="false">A quote</blockquote>
  <blockquote data-favorite="true">A favorite quote</blockquote>
  <blockquote data-favorite="false">A quote</blockquote>
  <blockquote data-favorite="false">A quote</blockquote>
</div>

<ul class="menu-first">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
  • $('.quotes + .menu-first')
  • $('.quotes .menu-first')
  • $('.quotes, .menu-first')
  • $('.quotes' + '.menu-first')

Effects like show, hide, fadIn, and fadeOut can be called with no arguments, but can also take arguments for how long they should last. Which is NOT a duration argument supported by these functions?

  • “fast”
  • “extreme”
  • 2000
  • “slow”

Though jQuery offers visual effects, it is considered a best practice to use CSS to set up different states triggered by classes, where it makes sense. What’s the easiest way to enable and disable a class bounce on an element with the ID dialog?

  • $('#dialog').classToggle('bounce')
  • $('#dialog.bounce').removeClass().addClass()
  • $('#dialog').addOrRemoveClass('bounce')
  • $('#dialog').toggleClass('bounce')

What is the main difference between selectors and filters?

  • Selectors are used to refine the content that filters have been applied to.
  • Selectors are used to find and select content in a page. Filters are used to refine the results of selectors.
  • Filters are used to remove content from the page. Selectors are used to add content to the page
  • There is no real difference. They are both used to build up lists of page content.

You want to create a custom right-click menu. How might you start the code?

  • $('#canvas').on('click.right', function(){ console.log('Handled a right-click') });
  • $('#canvas').on('contextual', function(){ console.log('Handled a right-click') });
  • $('#canvas').on('contextmenu', function(){ console.log('Handled a right-click') });
  • $('#canvas').on('rightclick', function(){ console.log('Handled a right-click') });

What is the correct way to check how many paragraphs exist on a page using jQuery?

  • $('p').count()
  • $('p').length
  • $('*').find('p')
  • $('p').length()

As with many areas of JavaScript, keeping track of the meaning of this is important and sometimes tricky. What does this mean at each of the two points in this custom plugin snippet?

$.fn.customPlugin = function() {
  // Point 1

  return this.each(function() {
    // Point 2
  })
}
$(document).customPlugin();
  • At Point 1, this means a jQuery object. At Point 2, it means a DOM element.
  • In this case, they mean the same thing: a jQuery object.
  • In this case, they mean the same thing: a DOM element.
  • At Point 1, this means a DOM element. At Point 2, it means a jQuery object.

How can you make the first list item bold and the next item oblique, in a single statement chain?

<ul class="menu-first">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>
  • [ ]
$('.menu-first > li')
  .eq(0)
  .css('font-weight', 'bold')
  .eq(1)
  .css('font-style', 'oblique');
  • [ ]
$('.menu-first > li')
  .first()
  .css('font-weight', 'bold')
  .after()
  .css('font-style', 'oblique');
  • [ ]
$('.menu-first > li')
  .first()
  .css('font-weight', 'bold')
  .second()
  .css('font-style', 'oblique');
  • [x]
$('.menu-first > li')
  .eq(0)
  .css('font-weight', 'bold')
  .next()
  .css('font-style', 'oblique');

Which CSS selectors can you NOT use in jQuery?

  • You cannot use multiple class selectors such as .class1.class2.
  • You cannot use pseudo-classes such as :not or :last-of-type.
  • You cannot use IDs and classes together, such as #element.class.
  • None. All CSS selectors are compatible in jQuery.

Starting with some DOM elements in the nested structure below, you assign listeners for the same event to a child element and one of the parents using the JavaScript that follows. You want to ensure that when .leaf is clicked, only its event handler will be fired, instead of the click bubbling up and also firing the parent’s click handler. What do you need to add to its handler function?

<ul class="items" id="main-menu">
  <li>Item 1<ul>
    <li class="leaf">Sub Item 1</li>
    <li>Sub Item 2</li>
  </ul></li>
</ul>
$('.leaf').click( function(event) { console.log('Sub Item 1 got a click'); } );
$('#main-menu').click( function(event) { console.log('Main menu got a click'); } );
  • event.capture();
  • event.stopPropagation();
  • event.preventDefault();
  • event.stop();

Using event delegation, you can listen for events on a lot of different items without having to attach separate listeners to each one. But there are times when you may want to check the type of item receiving the event before doing anything, such as checking if an image was clicked versus a text field. Given the starter code below, which choice shows what jQuery provides to help with that process?

<div id="sidebar">
  <img src="fancy-button.png" alt="Pick Me">
  <input type="text" placeholder="Fill in something">
</div>
$('#sidebar').click(function(evt) {
  var $target = $(evt.target);

  // What goes here?
});
  • $($target.get(0) + ':image')
  • $('img').is($target)
  • $target.filter('img')
  • $target.is('img')

There are many ways to create elements that can be added to the page. Which answer is NOT one of those ways, assuming you have the following on the page?

<div id="elements"></div>
  • [ ]
$("#elements").append($('<p class="appended">As an HTML string</p>'));
  • [ ]
var p = document.createElement('p');
var text = document.createTextNode('As a DOM element');
p.appendChild(text);
$("#elements").append(p);
  • [x]
$("#elements").append(<p class="appended">As a JSX object</p>);
  • [ ]
$("#elements").append($('<p>', {
  "class": 'appended',
  'text': "As an attribute object"
}));

The .addClass() and .removeClass() methods can accept functions as arguments. What does this function do?

$('#menu').addClass(function() {
  return $('body').attr('class');
});
  • It adds the first class found on the body element to the #menu element.
  • It adds all classes found on the #menu element to the body tag.
  • It replaces any classes on the #menu element with all classes from the body tag.
  • It adds all classes found on the body element to the #menu element.

You’re working on a site that uses an old version of jQuery, and you want to update to a newer version. What’s the most efficient way to do so?

  • Install the newer version of jQuery, go through each script one by one, and fix what looks broken.
  • Read the change notes for the newer version of jQuery, fix all scripts, install the newer version, and fix anything that remains broken.
  • Install the newer version of jQuery as well as its Migrate plugin, fix all warnings, and uninstall the Migrate plugin.
  • Install the newer version of jQuery at the same time, and use jQuery.noConflict() on pages that need the older version.

Let’s say you have a page with just one link on it. How can you change the anchor tag so it links to example.com?

  • $('a').attribute('href', 'http://www.example.com')
  • $('a').attr('href', 'http://www.example.com')
  • $('a').data('href', 'http://www.example.com')
  • $('a').href('http://www.example.com')

What does $() mean in jQuery?

  • It is an alias to the main core method of jQuery itself—the same as writing jQuery().
  • It is a utility function that selects the first element from the document.
  • It is a shorter way to write document.getElementById().
  • It is a utility function that selects the last element from the document.

Along with DOM traversal and manipulation, jQuery offers several general-purpose helper functions that fill in some JavaScript gaps, especially before ES2015. Which is NOT a jQuery utility function?

  • jQuery.each, a general purpose iterator for looping over arrays or objects
  • jQuery.isNumeric, which can check whether its argument is, or looks like, a number
  • jQuery.extend, which can merge objects and make complete deep copies of objects
  • jQuery.isMobile, which can tell whether the user is using a mobile browser

Given this set of checkboxes, how can you select the ones that have the phrase “sun” as part of the value?

<input type="checkbox" name="artists[]" value="sun-ra">
<input type="checkbox" name="artists[]" value="otis-redding">
<input type="checkbox" name="artists[]" value="captain-beefheart">
<input type="checkbox" name="artists[]" value="king-sunny-ade">
<input type="checkbox" name="artists[]" value="weather-report">
  • $('checkbox').val(/sun/);
  • $('input[value*="sun"]');
  • $('input[value|="sun"]');
  • $('input:checkbox').attr('value', '*sun*');

How can you get an AJAX request to go through without triggering any of jQuery’s AJAX events?

  • Set the type option to “none”.
  • Set the processData option to false.
  • Set a success callback that returns false.
  • Set the option “global” to false.

How do you change the current value of a text field with the class .form-item to “555-1212”?

  • $.val('.form-item', '555-1212');
  • $('.form-item').val('555-1212');
  • $('.form-item').data('value', '555-1212');
  • $('.form-item').set('value', '555-1212');

How would you fire a callback when any AJAX request on a page has completed?

  • $('body').ajaxComplete(function() { console.count('An AJAX request completed'); });
  • $(document).on('ajax-complete', function() { console.count('An AJAX request completed'); });
  • $('body').on('ajaxComplete', function() { console.count('An AJAX request completed'); });
  • $(document).ajaxComplete(function() { console.count('An AJAX request completed'); });

Given this set of checkboxes, how can you select the one with the value “blimp”?

<input type="checkbox" name="songs[]" value="satisfaction">
<input type="checkbox" name="songs[]" value="respect">
<input type="checkbox" name="songs[]" value="blimp">
<input type="checkbox" name="songs[]" value="saturn">
<input type="checkbox" name="songs[]" value="penguins">
  • $('input[value="blimp"]');
  • $('input[value!="blimp"]');
  • $('checkbox').val('blimp');
  • $('input:checkbox').attr('value', 'blimp');

Given this snippet of HTML and jQuery code, what does the jQuery do?

<ul class="menu">
  <li><a href="#" class="active">Home</a></li>
  <li><a href="#">Page 2</a></li>
</ul>
<ul class="active submenu">
  <li><a href="#">Subpage 1</a></li>
  <li><a href="#">Subpage 2</a></li>
</ul>
var m = $('.menu'), sm = $('.submenu');
m.add(sm);
m.css('font-weight', 'bold');
  • It makes all the menu items bold.
  • It throws an exception on line 3.
  • It makes the first set of menu items, not the second, bold.
  • It makes the second set of menu items, not the first, bold.

You want to take a block of type and animate it to a larger size with jQuery. The following HTML and JavaScript behaves strangely. What is the issue?

<div id="type" style="font: 1em/1.5 helvetica, arial, sans-serif; background: #ffc; padding: 0">
  Animate me!
</div>
$('#type').animate({
  fontSize: '+=1em'
}, 3000);
  • jQuery does not support ems and will make the type 1 pixel larger instead of 1 em larger.
  • jQuery cannot override CSS in a style attribute, so the font size will not change.
  • The font size was set with a shorthand property, so jQuery will not animate the font size at all.
  • The font size was set with a shorthand property, so jQuery will start the animation from 0 instead of from 1 em.

When using the clone() function to duplicate an element, what is one of the main concerns your code needs to watch out for?

  • The clone() function may ignore data attributes on the original elements.
  • The clone() function may result in elements with duplicate ID attributes.
  • The clone() function may remove CSS classes from the cloned elements.
  • The clone() function may not respect the attribute order of the original elements.

When incorporating a plugin into a project, what are the important steps for basic installation and usage?

  • The jQuery script tag must come first, followed by the plugin, followed by your custom scripts, all preferably at or near the bottom of the page.
  • Your custom scripts must appear first in the document <head>, followed by jQuery, followed by the plugin.
  • The jQuery script tag and the plugin script tag must appear in the document <head>, and your custom scripts can follow anywhere on the page.
  • The jQuery script tag must appear in the document <head>, but the plugin and your custom scripts can appear anywhere else in any order.

These two script tags show different ways of using jQuery’s ready() method. What is true about both approaches?

<script>
  $(function() {
    // The rest of my code goes here
  });
</script>

<script>
  jQuery(document).ready(function($) {
    // The rest of my code goes here
  });
</script>
  • The code inside them can manipulate the DOM safely, knowing the browser has loaded it fully.
  • The code inside them can manipulate images on the page safely, knowing they have fully downloaded to the browser.
  • The code inside them will be run exactly once per user session.
  • The code inside them is not aware of the DOM.

Which property of the jQuery event object references the DOM object that dispatched an event?

  • self
  • target
  • object
  • source

Which describes how jQuery makes working with the DOM faster?

  • jQuery optimizes the DOM in a background thread, making updates faster.
  • jQuery avoids using the DOM at all.
  • jQuery uses a virtual DOM that batches updates, making inserts and deletes faster.
  • jQuery code to perform DOM manipulation is shorter and easier to write, but does not make DOM operations faster.

There are some issues with this snippet of jQuery. First, it is manipulating CSS directly, rather than manipulating classes and leaving the CSS in stylesheets. What else in this code is best to avoid?

$('.item').css('background-color', 'red');
// some other code here
var firstSubItem = $('.item').find('.sub-item').get(0);
// some other code here too
$('.item').parents('.navigation').css('font-weight', 'bold');
  • The .css() method accepts only an object, not two separate arguments. This will trigger an exception that should be caught.
  • The $('.item') selection is being made several times. This should be cached in a variable for (however slightly) better performance and easier maintainability.
  • The call to .parents() is in an inefficient place.
  • All the calls to $('.item') should be chained together as a single executable line for better performance.

Which choice is an example of statement chaining?

  • var $p = $('p'); console.log($p.length);
  • $('p').find('a').children('li');
  • $('p > a > li');
  • $('p'); $('a'); $('li');

How can you ensure that some code executes only when a class active appears on an element?

  • $('.element').attr('class', 'active')
  • $('.element').with('.active')
  • $('.element').hasClass('active')
  • $('.active').then()

jQuery has a main function for handling AJAX, and several shorthand function including load() that make calling that main function easier. Given this HTML snippet, how can you insert only the second snippet from the source.html file (div#one) into the #load-me div on-demand via AJAX?

<div id="load-me">
  This area will be replaced with AJAX loaded content.
</div>

<div id="one">
  <h1>First Piece</h1>

  <p>
    Lorem ipsum duis maximus quam condimentum dolor eleifend scelerisque.
  </p>
</div>

<div id="two">
  <h1>Second Piece</h1>

  <p>
    Lorem ipsum proin facilisis augue in risus interdum ornare.
  </p>
</div>
  • $('#load-me').get('source.html#one');
  • $('#load-me').get('source.html #one');
  • $('#load-me').load('source.html #one');
  • $('#load-me').load('source.html', '#one');

Given this HTML list and subsequent two lines of jQuery, what is the difference in the behavior of .closest() and .parents()?

<ul class="items" id="main-menu">
  <li>Item 1 <ul id="sub-menu">
  <li class="leaf">Sub Item 1</li>
  <li>Sub Item 2</li>
  </ul></li>
</ul>
$('.leaf').closest('.items');
$('.leaf').parents('.items');
  • .closest() returns .leaf and #main-menu; .parents() returns #main-menu and #sub-menu.
  • .closest() returns .leaf and #sub-menu; .parents() returns #main-menu and #sub-menu.
  • .closest() returns only #main-menu; .parents() returns #main-menu and #sub-menu.
  • .closest() returns only #sub-menu; .parents() returns #main-menu and #sub-menu.

What does this line of code do?

$('ul > li:first-child');
  • selects the first list item inside all unordered lists on the page
  • selects the first list item inside the first unordered list on the page
  • selects the first element inside any list items on the page
  • creates a predefined CSS selector that can be reused later

Below is a list of items that you want to be clickable and an event handler function. How can you assign the event handler to every item in the list in a way that is most performant, and also that ensures that the handler is called even if more items are added to the list programmatically?

<ul class="clickable-list">
  <li>First Item</li>
  <li>Second Item</li>
  <li>Third Item</li>
  <li>Fourth Item</li>
  <li>Fifth Item</li>
</ul>
function listResponder(evt) {
  console.log('You clicked a list item that says', evt.target.innerText);
}
  • $('.clickable-list).click(listResponder);
  • $('.clickable-list).on('click', 'li', listResponder);
  • $('.clickable-list).on('click, append', listResponder);
  • $('.clickable-list).each(function() { $(this).click(listResponder); });
Spread the love